-
Notifications
You must be signed in to change notification settings - Fork 486
/
DialogManager.cs
403 lines (343 loc) · 16.8 KB
/
DialogManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs.Memory;
using Microsoft.Bot.Builder.Skills;
using Microsoft.Bot.Builder.TraceExtensions;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
namespace Microsoft.Bot.Builder.Dialogs
{
/// <summary>
/// Class which runs the dialog system.
/// </summary>
public class DialogManager
{
private const string LastAccess = "_lastAccess";
private string _rootDialogId;
private readonly string _dialogStateProperty;
/// <summary>
/// Initializes a new instance of the <see cref="DialogManager"/> class.
/// </summary>
/// <param name="rootDialog">Root dialog to use.</param>
/// <param name="dialogStateProperty">alternate name for the dialogState property. (Default is "DialogState").</param>
public DialogManager(Dialog rootDialog = null, string dialogStateProperty = null)
{
if (rootDialog != null)
{
RootDialog = rootDialog;
}
_dialogStateProperty = dialogStateProperty ?? "DialogState";
}
/// <summary>
/// Gets or sets the ConversationState.
/// </summary>
/// <value>
/// The ConversationState.
/// </value>
public ConversationState ConversationState { get; set; }
/// <summary>
/// Gets or sets the UserState.
/// </summary>
/// <value>
/// The UserState.
/// </value>
public UserState UserState { get; set; }
/// <summary>
/// Gets InitialTurnState collection to copy into the TurnState on every turn.
/// </summary>
/// <value>
/// TurnState.
/// </value>
public TurnContextStateCollection InitialTurnState { get; } = new TurnContextStateCollection();
/// <summary>
/// Gets or sets root dialog to use to start conversation.
/// </summary>
/// <value>
/// Root dialog to use to start conversation.
/// </value>
public Dialog RootDialog
{
get
{
if (_rootDialogId != null)
{
return Dialogs.Find(_rootDialogId);
}
return null;
}
set
{
Dialogs = new DialogSet();
if (value != null)
{
_rootDialogId = value.Id;
Dialogs.TelemetryClient = value.TelemetryClient;
Dialogs.Add(value);
}
else
{
_rootDialogId = null;
}
}
}
/// <summary>
/// Gets or sets global dialogs that you want to have be callable.
/// </summary>
/// <value>Dialogs set.</value>
[JsonIgnore]
public DialogSet Dialogs { get; set; } = new DialogSet();
/// <summary>
/// Gets or sets the DialogStateManagerConfiguration.
/// </summary>
/// <value>
/// The DialogStateManagerConfiguration.
/// </value>
public DialogStateManagerConfiguration StateConfiguration { get; set; }
/// <summary>
/// Gets or sets (optional) number of milliseconds to expire the bot's state after.
/// </summary>
/// <value>
/// Number of milliseconds.
/// </value>
public int? ExpireAfter { get; set; }
/// <summary>
/// Runs dialog system in the context of an ITurnContext.
/// </summary>
/// <param name="context">turn context.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>result of the running the logic against the activity.</returns>
public async Task<DialogManagerResult> OnTurnAsync(ITurnContext context, CancellationToken cancellationToken = default)
{
var botStateSet = new BotStateSet();
// Preload TurnState with DM TurnState.
foreach (var pair in InitialTurnState)
{
context.TurnState.Set(pair.Key, pair.Value);
}
// register DialogManager with TurnState.
context.TurnState.Set(this);
if (ConversationState == null)
{
ConversationState = context.TurnState.Get<ConversationState>() ?? throw new ArgumentNullException(nameof(ConversationState));
}
else
{
context.TurnState.Set(ConversationState);
}
botStateSet.Add(ConversationState);
if (UserState == null)
{
UserState = context.TurnState.Get<UserState>();
}
else
{
context.TurnState.Set(UserState);
}
if (UserState != null)
{
botStateSet.Add(UserState);
}
// create property accessors
var lastAccessProperty = ConversationState.CreateProperty<DateTime>(LastAccess);
var lastAccess = await lastAccessProperty.GetAsync(context, () => DateTime.UtcNow, cancellationToken).ConfigureAwait(false);
// Check for expired conversation
if (ExpireAfter.HasValue && (DateTime.UtcNow - lastAccess) >= TimeSpan.FromMilliseconds((double)ExpireAfter))
{
// Clear conversation state
await ConversationState.ClearStateAsync(context, cancellationToken).ConfigureAwait(false);
}
lastAccess = DateTime.UtcNow;
await lastAccessProperty.SetAsync(context, lastAccess, cancellationToken).ConfigureAwait(false);
// get dialog stack
var dialogsProperty = ConversationState.CreateProperty<DialogState>(_dialogStateProperty);
var dialogState = await dialogsProperty.GetAsync(context, () => new DialogState(), cancellationToken).ConfigureAwait(false);
// Create DialogContext
var dc = new DialogContext(Dialogs, context, dialogState);
// promote initial TurnState into dc.services for contextual services
foreach (var service in dc.Services)
{
dc.Services[service.Key] = service.Value;
}
// map TurnState into root dialog context.services
foreach (var service in context.TurnState)
{
dc.Services[service.Key] = service.Value;
}
// get the DialogStateManager configuration
var dialogStateManager = new DialogStateManager(dc, StateConfiguration);
await dialogStateManager.LoadAllScopesAsync(cancellationToken).ConfigureAwait(false);
dc.Context.TurnState.Add(dialogStateManager);
DialogTurnResult turnResult = null;
// Loop as long as we are getting valid OnError handled we should continue executing the actions for the turn.
//
// NOTE: We loop around this block because each pass through we either complete the turn and break out of the loop
// or we have had an exception AND there was an OnError action which captured the error. We need to continue the
// turn based on the actions the OnError handler introduced.
var endOfTurn = false;
while (!endOfTurn)
{
try
{
if (context.TurnState.Get<IIdentity>(BotAdapter.BotIdentityKey) is ClaimsIdentity claimIdentity && SkillValidation.IsSkillClaim(claimIdentity.Claims))
{
// The bot is running as a skill.
turnResult = await HandleSkillOnTurnAsync(dc, cancellationToken).ConfigureAwait(false);
}
else
{
// The bot is running as root bot.
turnResult = await HandleBotOnTurnAsync(dc, cancellationToken).ConfigureAwait(false);
}
// turn successfully completed, break the loop
endOfTurn = true;
}
catch (Exception err)
{
// fire error event, bubbling from the leaf.
var handled = await dc.EmitEventAsync(DialogEvents.Error, err, bubble: true, fromLeaf: true, cancellationToken: cancellationToken).ConfigureAwait(false);
if (!handled)
{
// error was NOT handled, throw the exception and end the turn. (This will trigger the Adapter.OnError handler and end the entire dialog stack)
throw;
}
}
}
// save all state scopes to their respective botState locations.
await dialogStateManager.SaveAllChangesAsync(cancellationToken).ConfigureAwait(false);
// save BotState changes
await botStateSet.SaveAllChangesAsync(dc.Context, false, cancellationToken).ConfigureAwait(false);
return new DialogManagerResult { TurnResult = turnResult };
}
/// <summary>
/// Helper to send a trace activity with a memory snapshot of the active dialog DC.
/// </summary>
private static async Task SendStateSnapshotTraceAsync(DialogContext dc, string traceLabel, CancellationToken cancellationToken)
{
// send trace of memory
var snapshot = GetActiveDialogContext(dc).State.GetMemorySnapshot();
var traceActivity = (Activity)Activity.CreateTraceActivity("BotState", "https://www.botframework.com/schemas/botState", snapshot, traceLabel);
await dc.Context.SendActivityAsync(traceActivity, cancellationToken).ConfigureAwait(false);
}
private static bool IsFromParentToSkill(ITurnContext turnContext)
{
if (turnContext.TurnState.Get<SkillConversationReference>(SkillHandler.SkillConversationReferenceKey) != null)
{
return false;
}
return turnContext.TurnState.Get<IIdentity>(BotAdapter.BotIdentityKey) is ClaimsIdentity claimIdentity && SkillValidation.IsSkillClaim(claimIdentity.Claims);
}
// Recursively walk up the DC stack to find the active DC.
private static DialogContext GetActiveDialogContext(DialogContext dialogContext)
{
var child = dialogContext.Child;
if (child == null)
{
return dialogContext;
}
return GetActiveDialogContext(child);
}
private async Task<DialogTurnResult> HandleSkillOnTurnAsync(DialogContext dc, CancellationToken cancellationToken)
{
// the bot is running as a skill.
var turnContext = dc.Context;
// Process remote cancellation
if (turnContext.Activity.Type == ActivityTypes.EndOfConversation && dc.ActiveDialog != null && IsFromParentToSkill(turnContext))
{
// Handle remote cancellation request from parent.
var activeDialogContext = GetActiveDialogContext(dc);
var remoteCancelText = "Skill was canceled through an EndOfConversation activity from the parent.";
await turnContext.TraceActivityAsync($"{GetType().Name}.OnTurnAsync()", label: $"{remoteCancelText}", cancellationToken: cancellationToken).ConfigureAwait(false);
// Send cancellation message to the top dialog in the stack to ensure all the parents are canceled in the right order.
return await activeDialogContext.CancelAllDialogsAsync(true, cancellationToken: cancellationToken).ConfigureAwait(false);
}
// Handle reprompt
// Process a reprompt event sent from the parent.
if (turnContext.Activity.Type == ActivityTypes.Event && turnContext.Activity.Name == DialogEvents.RepromptDialog)
{
if (dc.ActiveDialog == null)
{
return new DialogTurnResult(DialogTurnStatus.Empty);
}
await dc.RepromptDialogAsync(cancellationToken).ConfigureAwait(false);
return new DialogTurnResult(DialogTurnStatus.Waiting);
}
// Continue execution
// - This will apply any queued up interruptions and execute the current/next step(s).
var turnResult = await dc.ContinueDialogAsync(cancellationToken).ConfigureAwait(false);
if (turnResult.Status == DialogTurnStatus.Empty)
{
// restart root dialog
var startMessageText = $"Starting {_rootDialogId}.";
await turnContext.TraceActivityAsync($"{GetType().Name}.OnTurnAsync()", label: $"{startMessageText}", cancellationToken: cancellationToken).ConfigureAwait(false);
turnResult = await dc.BeginDialogAsync(_rootDialogId, cancellationToken: cancellationToken).ConfigureAwait(false);
}
await SendStateSnapshotTraceAsync(dc, "Skill State", cancellationToken).ConfigureAwait(false);
if (ShouldSendEndOfConversationToParent(turnContext, turnResult))
{
var endMessageText = $"Dialog {_rootDialogId} has **completed**. Sending EndOfConversation.";
await turnContext.TraceActivityAsync($"{GetType().Name}.OnTurnAsync()", label: $"{endMessageText}", value: turnResult.Result, cancellationToken: cancellationToken).ConfigureAwait(false);
// Send End of conversation at the end.
var activity = new Activity(ActivityTypes.EndOfConversation)
{
Value = turnResult.Result,
Locale = turnContext.Activity.Locale
};
await turnContext.SendActivityAsync(activity, cancellationToken).ConfigureAwait(false);
}
return turnResult;
}
private async Task<DialogTurnResult> HandleBotOnTurnAsync(DialogContext dc, CancellationToken cancellationToken)
{
DialogTurnResult turnResult;
// the bot is running as a root bot.
if (dc.ActiveDialog == null)
{
// start root dialog
turnResult = await dc.BeginDialogAsync(_rootDialogId, cancellationToken: cancellationToken).ConfigureAwait(false);
}
else
{
// Continue execution
// - This will apply any queued up interruptions and execute the current/next step(s).
turnResult = await dc.ContinueDialogAsync(cancellationToken).ConfigureAwait(false);
if (turnResult.Status == DialogTurnStatus.Empty)
{
// restart root dialog
turnResult = await dc.BeginDialogAsync(_rootDialogId, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
await SendStateSnapshotTraceAsync(dc, "Bot State", cancellationToken).ConfigureAwait(false);
return turnResult;
}
/// <summary>
/// Helper to determine if we should send an EndOfConversation to the parent or not.
/// </summary>
private bool ShouldSendEndOfConversationToParent(ITurnContext context, DialogTurnResult turnResult)
{
if (!(turnResult.Status == DialogTurnStatus.Complete || turnResult.Status == DialogTurnStatus.Cancelled))
{
// The dialog is still going, don't return EoC.
return false;
}
if (context.TurnState.Get<IIdentity>(BotAdapter.BotIdentityKey) is ClaimsIdentity claimIdentity && SkillValidation.IsSkillClaim(claimIdentity.Claims))
{
// EoC Activities returned by skills are bounced back to the bot by SkillHandler.
// In those cases we will have a SkillConversationReference instance in state.
var skillConversationReference = context.TurnState.Get<SkillConversationReference>(SkillHandler.SkillConversationReferenceKey);
if (skillConversationReference != null)
{
// If the skillConversationReference.OAuthScope is for one of the supported channels, we are at the root and we should not send an EoC.
return skillConversationReference.OAuthScope != AuthenticationConstants.ToChannelFromBotOAuthScope && skillConversationReference.OAuthScope != GovernmentAuthenticationConstants.ToChannelFromBotOAuthScope;
}
return true;
}
return false;
}
}
}