-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentSessionService.cs
More file actions
1070 lines (952 loc) · 43.3 KB
/
AgentSessionService.cs
File metadata and controls
1070 lines (952 loc) · 43.3 KB
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using DotPilot.Core.AgentBuilder;
using DotPilot.Core.ControlPlaneDomain;
using DotPilot.Core.Providers;
using ManagedCode.Communication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotPilot.Core.ChatSessions;
internal sealed class AgentSessionService(
IDbContextFactory<LocalAgentSessionDbContext> dbContextFactory,
AgentExecutionLoggingMiddleware executionLoggingMiddleware,
ISessionActivityMonitor sessionActivityMonitor,
IAgentProviderStatusReader providerStatusReader,
AgentRuntimeConversationFactory runtimeConversationFactory,
TimeProvider timeProvider,
ILogger<AgentSessionService> logger)
: IAgentSessionService, IDisposable
{
private const string NotYetImplementedFormat = "{0} live CLI execution is not wired yet in this slice.";
private const string SessionReadyText = "Session created. Send the first message to start the workflow.";
private const string UserAuthor = "You";
private const string ToolAuthor = "Tool";
private const string StatusAuthor = "System";
private const string DisabledProviderSendText = "The provider for this agent is disabled. Re-enable it in settings before sending.";
private const string ToolAccentLabel = "tool";
private const string StatusAccentLabel = "status";
private const string ErrorAccentLabel = "error";
internal static readonly System.Text.CompositeFormat LiveExecutionUnavailableCompositeFormat =
System.Text.CompositeFormat.Parse(NotYetImplementedFormat);
private readonly SemaphoreSlim _initializationGate = new(1, 1);
private bool _initialized;
public async ValueTask<Result<AgentWorkspaceSnapshot>> GetWorkspaceAsync(CancellationToken cancellationToken)
{
return await LoadWorkspaceAsync(forceRefreshProviders: false, cancellationToken);
}
public async ValueTask<Result<AgentWorkspaceSnapshot>> RefreshWorkspaceAsync(CancellationToken cancellationToken)
{
return await LoadWorkspaceAsync(forceRefreshProviders: true, cancellationToken);
}
private async ValueTask<Result<AgentWorkspaceSnapshot>> LoadWorkspaceAsync(
bool forceRefreshProviders,
CancellationToken cancellationToken)
{
try
{
await EnsureInitializedAsync(cancellationToken);
await using var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
var agents = await dbContext.AgentProfiles
.ToListAsync(cancellationToken);
agents = OrderAgents(agents);
var sessions = (await dbContext.Sessions
.ToListAsync(cancellationToken))
.OrderByDescending(record => record.UpdatedAt)
.ToList();
var entries = (await dbContext.SessionEntries
.ToListAsync(cancellationToken))
.OrderBy(record => record.Timestamp)
.ToList();
var agentsById = agents.ToDictionary(record => record.Id);
var sessionItems = sessions
.Select(record => MapSessionListItem(record, agentsById, entries))
.ToArray();
var providers = await GetProviderStatusesAsync(forceRefreshProviders, cancellationToken);
AgentSessionServiceLog.WorkspaceLoaded(
logger,
sessionItems.Length,
agents.Count,
providers.Count);
return Result<AgentWorkspaceSnapshot>.Succeed(new AgentWorkspaceSnapshot(
sessionItems,
agents.Select(MapAgentSummary).ToArray(),
providers,
sessionItems.Length > 0 ? sessionItems[0].Id : null));
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception exception)
{
AgentSessionServiceLog.WorkspaceLoadFailed(logger, exception);
return Result<AgentWorkspaceSnapshot>.Fail(exception);
}
}
public async ValueTask<Result<SessionTranscriptSnapshot>> GetSessionAsync(SessionId sessionId, CancellationToken cancellationToken)
{
try
{
await EnsureInitializedAsync(cancellationToken);
await using var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
var session = await dbContext.Sessions
.FirstOrDefaultAsync(record => record.Id == sessionId.Value, cancellationToken);
if (session is null)
{
AgentSessionServiceLog.SessionNotFound(logger, sessionId);
return Result<SessionTranscriptSnapshot>.FailNotFound($"Session '{sessionId}' was not found.");
}
var agents = await dbContext.AgentProfiles
.Where(record => record.Id == session.PrimaryAgentProfileId)
.ToListAsync(cancellationToken);
var agentsById = agents.ToDictionary(record => record.Id);
var entries = (await dbContext.SessionEntries
.Where(record => record.SessionId == sessionId.Value)
.ToListAsync(cancellationToken))
.OrderBy(record => record.Timestamp)
.ToList();
var snapshot = new SessionTranscriptSnapshot(
MapSessionListItem(session, agentsById, entries),
entries.Select(MapEntry).ToArray(),
agents.Select(MapAgentSummary).ToArray());
AgentSessionServiceLog.SessionLoaded(
logger,
sessionId,
snapshot.Entries.Count,
snapshot.Participants.Count);
return Result<SessionTranscriptSnapshot>.Succeed(snapshot);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception exception)
{
AgentSessionServiceLog.SessionLoadFailed(logger, exception, sessionId);
return Result<SessionTranscriptSnapshot>.Fail(exception);
}
}
public async ValueTask<Result<AgentProfileSummary>> CreateAgentAsync(
CreateAgentProfileCommand command,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command);
await EnsureInitializedAsync(cancellationToken);
var agentName = command.Name.Trim();
var modelName = command.ModelName.Trim();
var systemPrompt = command.SystemPrompt.Trim();
var description = ResolveAgentDescription(command.Description, systemPrompt);
AgentSessionServiceLog.AgentCreationStarted(logger, agentName, command.ProviderKind);
try
{
await using var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
var providers = await GetProviderStatusesAsync(forceRefresh: false, cancellationToken);
var provider = providers.First(status => status.Kind == command.ProviderKind);
if (!provider.CanCreateAgents)
{
return Result<AgentProfileSummary>.FailForbidden(provider.StatusSummary);
}
var createdAt = timeProvider.GetUtcNow();
var record = new AgentProfileRecord
{
Id = Guid.CreateVersion7(),
Name = agentName,
Description = description,
Role = AgentProfileSchemaDefaults.DefaultRole,
ProviderKind = (int)command.ProviderKind,
ModelName = modelName,
SystemPrompt = systemPrompt,
CapabilitiesJson = AgentProfileSchemaDefaults.EmptyCapabilitiesJson,
CreatedAt = createdAt,
};
dbContext.AgentProfiles.Add(record);
await dbContext.SaveChangesAsync(cancellationToken);
AgentSessionServiceLog.AgentCreated(
logger,
record.Id,
record.Name,
command.ProviderKind);
return Result<AgentProfileSummary>.Succeed(MapAgentSummary(record));
}
catch (Exception exception)
{
AgentSessionServiceLog.AgentCreationFailed(logger, exception, agentName, command.ProviderKind);
return Result<AgentProfileSummary>.Fail(exception);
}
}
public async ValueTask<Result<AgentProfileSummary>> UpdateAgentAsync(
UpdateAgentProfileCommand command,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command);
await EnsureInitializedAsync(cancellationToken);
var agentName = command.Name.Trim();
var modelName = command.ModelName.Trim();
var systemPrompt = command.SystemPrompt.Trim();
var description = ResolveAgentDescription(command.Description, systemPrompt);
AgentSessionServiceLog.AgentUpdateStarted(logger, command.AgentId, agentName, command.ProviderKind);
try
{
await using var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
var record = await dbContext.AgentProfiles
.FirstOrDefaultAsync(agent => agent.Id == command.AgentId.Value, cancellationToken);
if (record is null)
{
return Result<AgentProfileSummary>.FailNotFound($"Agent '{command.AgentId}' was not found.");
}
var providers = await GetProviderStatusesAsync(forceRefresh: false, cancellationToken);
var provider = providers.First(status => status.Kind == command.ProviderKind);
if (!provider.CanCreateAgents)
{
return Result<AgentProfileSummary>.FailForbidden(provider.StatusSummary);
}
record.Name = agentName;
record.Description = description;
record.ProviderKind = (int)command.ProviderKind;
record.ModelName = modelName;
record.SystemPrompt = systemPrompt;
await dbContext.SaveChangesAsync(cancellationToken);
AgentSessionServiceLog.AgentUpdated(
logger,
record.Id,
record.Name,
command.ProviderKind);
return Result<AgentProfileSummary>.Succeed(MapAgentSummary(record));
}
catch (Exception exception)
{
AgentSessionServiceLog.AgentUpdateFailed(logger, exception, command.AgentId, agentName, command.ProviderKind);
return Result<AgentProfileSummary>.Fail(exception);
}
}
public async ValueTask<Result<SessionTranscriptSnapshot>> CreateSessionAsync(
CreateSessionCommand command,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command);
try
{
await EnsureInitializedAsync(cancellationToken);
var sessionTitle = command.Title.Trim();
AgentSessionServiceLog.SessionCreationStarted(logger, sessionTitle, command.AgentProfileId);
await using var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
var agent = await dbContext.AgentProfiles
.FirstOrDefaultAsync(record => record.Id == command.AgentProfileId.Value, cancellationToken);
if (agent is null)
{
return Result<SessionTranscriptSnapshot>.FailNotFound($"Agent '{command.AgentProfileId}' was not found.");
}
var now = timeProvider.GetUtcNow();
var sessionId = SessionId.New();
var session = new SessionRecord
{
Id = sessionId.Value,
Title = sessionTitle,
PrimaryAgentProfileId = agent.Id,
CreatedAt = now,
UpdatedAt = now,
};
dbContext.Sessions.Add(session);
dbContext.SessionEntries.Add(CreateEntryRecord(sessionId, SessionStreamEntryKind.Status, StatusAuthor, SessionReadyText, now, accentLabel: StatusAccentLabel));
await dbContext.SaveChangesAsync(cancellationToken);
AgentSessionServiceLog.SessionCreated(logger, sessionId, session.Title, command.AgentProfileId);
var reloaded = await GetSessionAsync(sessionId, cancellationToken);
return reloaded.IsSuccess
? reloaded
: Result<SessionTranscriptSnapshot>.Fail("SessionCreationFailed", "Created session could not be reloaded.");
}
catch (Exception exception)
{
AgentSessionServiceLog.SessionCreationFailed(logger, exception, command.Title, command.AgentProfileId);
return Result<SessionTranscriptSnapshot>.Fail(exception);
}
}
public async ValueTask<Result<ProviderStatusDescriptor>> UpdateProviderAsync(
UpdateProviderPreferenceCommand command,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command);
await EnsureInitializedAsync(cancellationToken);
try
{
await using var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
var record = await dbContext.ProviderPreferences
.FirstOrDefaultAsync(preference => preference.ProviderKind == (int)command.ProviderKind, cancellationToken);
if (record is null)
{
record = new ProviderPreferenceRecord
{
ProviderKind = (int)command.ProviderKind,
};
dbContext.ProviderPreferences.Add(record);
}
record.IsEnabled = command.IsEnabled;
record.UpdatedAt = timeProvider.GetUtcNow();
await dbContext.SaveChangesAsync(cancellationToken);
InvalidateProviderStatusSnapshot();
var providers = await GetProviderStatusesAsync(forceRefresh: true, cancellationToken);
var provider = providers.First(status => status.Kind == command.ProviderKind);
AgentSessionServiceLog.ProviderPreferenceUpdated(logger, command.ProviderKind, command.IsEnabled);
return Result<ProviderStatusDescriptor>.Succeed(provider);
}
catch (Exception exception)
{
AgentSessionServiceLog.ProviderPreferenceUpdateFailed(
logger,
exception,
command.ProviderKind,
command.IsEnabled);
return Result<ProviderStatusDescriptor>.Fail(exception);
}
}
public async IAsyncEnumerable<Result<SessionStreamEntry>> SendMessageAsync(
SendSessionMessageCommand command,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command);
Result initializeResult;
try
{
await EnsureInitializedAsync(cancellationToken);
initializeResult = Result.Succeed();
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, Guid.Empty);
initializeResult = Result.Fail(exception);
}
if (initializeResult.IsFailed)
{
yield return Result<SessionStreamEntry>.Fail(initializeResult.Problem!);
yield break;
}
LocalAgentSessionDbContext? dbContext = null;
Result dbContextResult;
try
{
dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
dbContextResult = Result.Succeed();
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, Guid.Empty);
dbContextResult = Result.Fail(exception);
}
if (dbContextResult.IsFailed || dbContext is null)
{
yield return Result<SessionStreamEntry>.Fail(dbContextResult.Problem!);
yield break;
}
await using (dbContext)
{
Result<(SessionRecord Session, AgentProfileRecord Agent, AgentSessionProviderProfile ProviderProfile, DateTimeOffset Timestamp)> contextResult;
try
{
var sessionRecord = await dbContext.Sessions
.FirstOrDefaultAsync(record => record.Id == command.SessionId.Value, cancellationToken);
if (sessionRecord is null)
{
contextResult = Result<(SessionRecord, AgentProfileRecord, AgentSessionProviderProfile, DateTimeOffset)>.FailNotFound(
$"Session '{command.SessionId}' was not found.");
}
else
{
var agentRecord = await dbContext.AgentProfiles
.FirstOrDefaultAsync(record => record.Id == sessionRecord.PrimaryAgentProfileId, cancellationToken);
if (agentRecord is null)
{
contextResult = Result<(SessionRecord, AgentProfileRecord, AgentSessionProviderProfile, DateTimeOffset)>.FailNotFound(
$"Agent '{sessionRecord.PrimaryAgentProfileId}' was not found.");
}
else
{
contextResult = Result<(SessionRecord, AgentProfileRecord, AgentSessionProviderProfile, DateTimeOffset)>.Succeed((
sessionRecord,
agentRecord,
AgentSessionProviderCatalog.Get((AgentProviderKind)agentRecord.ProviderKind),
timeProvider.GetUtcNow()));
}
}
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, Guid.Empty);
contextResult = Result<(SessionRecord, AgentProfileRecord, AgentSessionProviderProfile, DateTimeOffset)>.Fail(exception);
}
if (contextResult.IsFailed)
{
yield return Result<SessionStreamEntry>.Fail(contextResult.Problem!);
yield break;
}
var (session, agent, providerProfile, now) = contextResult.Value;
AgentSessionServiceLog.SendStarted(
logger,
command.SessionId,
agent.Id,
providerProfile.Kind);
Result<SessionEntryRecord> userEntryResult;
try
{
var userEntry = CreateEntryRecord(command.SessionId, SessionStreamEntryKind.UserMessage, UserAuthor, command.Message.Trim(), now);
dbContext.SessionEntries.Add(userEntry);
session.UpdatedAt = now;
await dbContext.SaveChangesAsync(cancellationToken);
userEntryResult = Result<SessionEntryRecord>.Succeed(userEntry);
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, agent.Id);
userEntryResult = Result<SessionEntryRecord>.Fail(exception);
}
if (userEntryResult.IsFailed)
{
yield return Result<SessionStreamEntry>.Fail(userEntryResult.Problem!);
yield break;
}
yield return Result<SessionStreamEntry>.Succeed(MapEntry(userEntryResult.Value));
var statusEntry = CreateEntryRecord(
command.SessionId,
SessionStreamEntryKind.Status,
StatusAuthor,
$"Running {agent.Name} with {providerProfile.DisplayName}.",
timeProvider.GetUtcNow(),
accentLabel: StatusAccentLabel);
Result<SessionStreamEntry> statusEntryResult;
try
{
dbContext.SessionEntries.Add(statusEntry);
session.UpdatedAt = statusEntry.Timestamp;
await dbContext.SaveChangesAsync(cancellationToken);
statusEntryResult = Result<SessionStreamEntry>.Succeed(MapEntry(statusEntry));
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, agent.Id);
statusEntryResult = Result<SessionStreamEntry>.Fail(exception);
}
if (statusEntryResult.IsFailed)
{
yield return statusEntryResult;
yield break;
}
yield return statusEntryResult;
Result<ProviderStatusDescriptor> providerStatusResult;
try
{
var providerStatuses = await GetProviderStatusesAsync(forceRefresh: false, cancellationToken);
providerStatusResult = Result<ProviderStatusDescriptor>.Succeed(
providerStatuses.First(status => status.Kind == providerProfile.Kind));
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, agent.Id);
providerStatusResult = Result<ProviderStatusDescriptor>.Fail(exception);
}
if (providerStatusResult.IsFailed)
{
yield return Result<SessionStreamEntry>.Fail(providerStatusResult.Problem!);
yield break;
}
var providerStatus = providerStatusResult.Value;
if (!providerStatus.IsEnabled)
{
AgentSessionServiceLog.SendBlockedDisabled(logger, command.SessionId, providerProfile.Kind);
var disabledEntry = CreateEntryRecord(
command.SessionId,
SessionStreamEntryKind.Error,
StatusAuthor,
DisabledProviderSendText,
timeProvider.GetUtcNow(),
accentLabel: ErrorAccentLabel);
dbContext.SessionEntries.Add(disabledEntry);
session.UpdatedAt = disabledEntry.Timestamp;
await dbContext.SaveChangesAsync(cancellationToken);
yield return Result<SessionStreamEntry>.Succeed(MapEntry(disabledEntry));
yield break;
}
if (!providerStatus.CanCreateAgents)
{
var unavailableEntry = CreateEntryRecord(
command.SessionId,
SessionStreamEntryKind.Error,
StatusAuthor,
providerStatus.StatusSummary,
timeProvider.GetUtcNow(),
accentLabel: ErrorAccentLabel);
dbContext.SessionEntries.Add(unavailableEntry);
session.UpdatedAt = unavailableEntry.Timestamp;
await dbContext.SaveChangesAsync(cancellationToken);
yield return Result<SessionStreamEntry>.Succeed(MapEntry(unavailableEntry));
yield break;
}
if (!providerProfile.SupportsLiveExecution)
{
AgentSessionServiceLog.SendBlockedNotWired(logger, command.SessionId, providerProfile.Kind);
var notImplementedEntry = CreateEntryRecord(
command.SessionId,
SessionStreamEntryKind.Error,
StatusAuthor,
string.Format(
System.Globalization.CultureInfo.InvariantCulture,
LiveExecutionUnavailableCompositeFormat,
providerProfile.DisplayName),
timeProvider.GetUtcNow(),
accentLabel: ErrorAccentLabel);
dbContext.SessionEntries.Add(notImplementedEntry);
session.UpdatedAt = notImplementedEntry.Timestamp;
await dbContext.SaveChangesAsync(cancellationToken);
yield return Result<SessionStreamEntry>.Succeed(MapEntry(notImplementedEntry));
yield break;
}
using var liveActivity = sessionActivityMonitor.BeginActivity(
new SessionActivityDescriptor(
command.SessionId,
session.Title,
new AgentProfileId(agent.Id),
agent.Name,
providerProfile.DisplayName));
Result<RuntimeConversationContext> runtimeConversationResult;
try
{
runtimeConversationResult = Result<RuntimeConversationContext>.Succeed(
await runtimeConversationFactory.LoadOrCreateAsync(agent, command.SessionId, cancellationToken));
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, agent.Id);
runtimeConversationResult = Result<RuntimeConversationContext>.Fail(exception);
}
if (runtimeConversationResult.IsFailed)
{
yield return Result<SessionStreamEntry>.Fail(runtimeConversationResult.Problem!);
yield break;
}
var runtimeConversation = runtimeConversationResult.Value;
var toolStartEntry = CreateEntryRecord(
command.SessionId,
SessionStreamEntryKind.ToolStarted,
ToolAuthor,
CreateToolStartText(providerProfile),
timeProvider.GetUtcNow(),
agentProfileId: new AgentProfileId(agent.Id),
accentLabel: ToolAccentLabel);
Result<SessionStreamEntry> toolStartEntryResult;
try
{
dbContext.SessionEntries.Add(toolStartEntry);
session.UpdatedAt = toolStartEntry.Timestamp;
await dbContext.SaveChangesAsync(cancellationToken);
toolStartEntryResult = Result<SessionStreamEntry>.Succeed(MapEntry(toolStartEntry));
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, agent.Id);
toolStartEntryResult = Result<SessionStreamEntry>.Fail(exception);
}
if (toolStartEntryResult.IsFailed)
{
yield return toolStartEntryResult;
yield break;
}
yield return toolStartEntryResult;
string? streamedMessageId = null;
SessionEntryRecord? streamedAssistantEntry = null;
var accumulated = new System.Text.StringBuilder();
var runConfiguration = executionLoggingMiddleware.CreateRunConfiguration(
runtimeConversation.Descriptor,
command.SessionId);
AgentSessionServiceLog.SendRunPrepared(
logger,
command.SessionId,
agent.Id,
runConfiguration.Context.RunId,
providerProfile.Kind,
agent.ModelName);
await using var updateEnumerator = runtimeConversation.Agent.RunStreamingAsync(
command.Message.Trim(),
runtimeConversation.Session,
runConfiguration.Options,
cancellationToken)
.GetAsyncEnumerator(cancellationToken);
while (true)
{
Microsoft.Agents.AI.AgentResponseUpdate? update = null;
Result<bool> nextUpdateResult;
try
{
var hasNext = await updateEnumerator.MoveNextAsync();
if (hasNext)
{
update = updateEnumerator.Current;
}
nextUpdateResult = Result<bool>.Succeed(hasNext);
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, agent.Id);
nextUpdateResult = Result<bool>.Fail(exception);
}
if (nextUpdateResult.IsFailed)
{
yield return Result<SessionStreamEntry>.Fail(nextUpdateResult.Problem!);
yield break;
}
if (!nextUpdateResult.Value)
{
break;
}
if (string.IsNullOrEmpty(update?.Text))
{
continue;
}
streamedMessageId ??= string.IsNullOrWhiteSpace(update.MessageId)
? Guid.CreateVersion7().ToString("N", System.Globalization.CultureInfo.InvariantCulture)
: update.MessageId;
accumulated.Append(update.Text);
Result<SessionStreamEntry> streamedEntryResult;
try
{
var timestamp = update.CreatedAt ?? timeProvider.GetUtcNow();
if (streamedAssistantEntry is null)
{
streamedAssistantEntry = new SessionEntryRecord
{
Id = streamedMessageId,
SessionId = command.SessionId.Value,
AgentProfileId = agent.Id,
Kind = (int)SessionStreamEntryKind.AssistantMessage,
Author = agent.Name,
Text = accumulated.ToString(),
Timestamp = timestamp,
};
dbContext.SessionEntries.Add(streamedAssistantEntry);
}
else
{
streamedAssistantEntry.Text = accumulated.ToString();
streamedAssistantEntry.Timestamp = timestamp;
}
session.UpdatedAt = timestamp;
await dbContext.SaveChangesAsync(cancellationToken);
streamedEntryResult = Result<SessionStreamEntry>.Succeed(MapEntry(streamedAssistantEntry));
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, agent.Id);
streamedEntryResult = Result<SessionStreamEntry>.Fail(exception);
}
if (streamedEntryResult.IsFailed)
{
yield return streamedEntryResult;
yield break;
}
yield return streamedEntryResult;
}
Result<SessionStreamEntry> completionResult;
try
{
await runtimeConversationFactory.SaveAsync(runtimeConversation, command.SessionId, cancellationToken);
if (streamedAssistantEntry is null)
{
streamedAssistantEntry = new SessionEntryRecord
{
Id = streamedMessageId ?? Guid.CreateVersion7().ToString("N", System.Globalization.CultureInfo.InvariantCulture),
SessionId = command.SessionId.Value,
AgentProfileId = agent.Id,
Kind = (int)SessionStreamEntryKind.AssistantMessage,
Author = agent.Name,
Text = accumulated.ToString(),
Timestamp = timeProvider.GetUtcNow(),
};
dbContext.SessionEntries.Add(streamedAssistantEntry);
}
else
{
streamedAssistantEntry.Text = accumulated.ToString();
streamedAssistantEntry.Timestamp = timeProvider.GetUtcNow();
}
var toolDoneEntry = CreateEntryRecord(
command.SessionId,
SessionStreamEntryKind.ToolCompleted,
ToolAuthor,
CreateToolDoneText(providerProfile),
timeProvider.GetUtcNow(),
agentProfileId: new AgentProfileId(agent.Id),
accentLabel: ToolAccentLabel);
dbContext.SessionEntries.Add(toolDoneEntry);
session.UpdatedAt = toolDoneEntry.Timestamp;
await dbContext.SaveChangesAsync(cancellationToken);
AgentSessionServiceLog.SendCompleted(logger, command.SessionId, agent.Id, accumulated.Length);
completionResult = Result<SessionStreamEntry>.Succeed(MapEntry(toolDoneEntry));
}
catch (Exception exception)
{
AgentSessionServiceLog.SendFailed(logger, exception, command.SessionId, agent.Id);
completionResult = Result<SessionStreamEntry>.Fail(exception);
}
yield return completionResult;
}
}
private async Task EnsureInitializedAsync(CancellationToken cancellationToken)
{
if (_initialized)
{
return;
}
await _initializationGate.WaitAsync(cancellationToken);
try
{
if (_initialized)
{
return;
}
AgentSessionServiceLog.InitializationStarted(logger);
await using var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
await dbContext.Database.EnsureCreatedAsync(cancellationToken);
await AgentProfileSchemaCompatibilityEnsurer.EnsureAsync(dbContext, cancellationToken);
await EnsureDefaultProviderAndAgentAsync(dbContext, cancellationToken);
_initialized = true;
AgentSessionServiceLog.InitializationCompleted(logger);
}
finally
{
_initializationGate.Release();
}
}
private async Task EnsureDefaultProviderAndAgentAsync(
LocalAgentSessionDbContext dbContext,
CancellationToken cancellationToken)
{
var hasEnabledProvider = await dbContext.ProviderPreferences
.AnyAsync(record => record.IsEnabled, cancellationToken);
if (!hasEnabledProvider)
{
await EnsureProviderEnabledAsync(dbContext, AgentProviderKind.Debug, cancellationToken);
}
await NormalizeLegacyAgentProfilesAsync(dbContext, cancellationToken);
var hasAgents = await dbContext.AgentProfiles.AnyAsync(cancellationToken);
if (hasAgents)
{
return;
}
var providerKind = await ResolveSeedProviderKindAsync(dbContext, cancellationToken);
if (providerKind == AgentProviderKind.Debug)
{
await EnsureProviderEnabledAsync(dbContext, providerKind, cancellationToken);
}
var record = new AgentProfileRecord
{
Id = Guid.CreateVersion7(),
Name = AgentSessionDefaults.SystemAgentName,
Description = AgentSessionDefaults.SystemAgentDescription,
Role = AgentProfileSchemaDefaults.DefaultRole,
ProviderKind = (int)providerKind,
ModelName = AgentSessionDefaults.GetDefaultModel(providerKind),
SystemPrompt = AgentSessionDefaults.SystemAgentPrompt,
CapabilitiesJson = AgentProfileSchemaDefaults.EmptyCapabilitiesJson,
CreatedAt = timeProvider.GetUtcNow(),
};
dbContext.AgentProfiles.Add(record);
await dbContext.SaveChangesAsync(cancellationToken);
AgentSessionServiceLog.DefaultAgentSeeded(logger, record.Id, providerKind, record.ModelName);
}
private async Task EnsureProviderEnabledAsync(
LocalAgentSessionDbContext dbContext,
AgentProviderKind providerKind,
CancellationToken cancellationToken)
{
var preference = await dbContext.ProviderPreferences
.FirstOrDefaultAsync(
record => record.ProviderKind == (int)providerKind,
cancellationToken);
if (preference is null)
{
preference = new ProviderPreferenceRecord
{
ProviderKind = (int)providerKind,
};
dbContext.ProviderPreferences.Add(preference);
}
if (preference.IsEnabled)
{
return;
}
preference.IsEnabled = true;
preference.UpdatedAt = timeProvider.GetUtcNow();
AgentSessionServiceLog.DefaultProviderEnabled(logger, providerKind);
await dbContext.SaveChangesAsync(cancellationToken);
}
private static async ValueTask<AgentProviderKind> ResolveSeedProviderKindAsync(
LocalAgentSessionDbContext dbContext,
CancellationToken cancellationToken)
{
var enabledProviderKinds = await dbContext.ProviderPreferences
.Where(record => record.IsEnabled)
.Select(record => (AgentProviderKind)record.ProviderKind)
.ToArrayAsync(cancellationToken);
foreach (var providerKind in enabledProviderKinds)
{
var profile = AgentSessionProviderCatalog.Get(providerKind);
if (!profile.SupportsLiveExecution || profile.IsBuiltIn)
{
continue;
}
if (!string.IsNullOrWhiteSpace(AgentSessionCommandProbe.ResolveExecutablePath(profile.CommandName)))
{
return providerKind;
}
}
return AgentProviderKind.Debug;
}
private async ValueTask<IReadOnlyList<ProviderStatusDescriptor>> GetProviderStatusesAsync(
bool forceRefresh,
CancellationToken cancellationToken)
{
return forceRefresh
? await providerStatusReader.RefreshAsync(cancellationToken)
: await providerStatusReader.ReadAsync(cancellationToken);
}
private void InvalidateProviderStatusSnapshot()
{
providerStatusReader.Invalidate();
}
private async Task NormalizeLegacyAgentProfilesAsync(
LocalAgentSessionDbContext dbContext,
CancellationToken cancellationToken)
{
var legacyDebugModel = AgentSessionDefaults.GetDefaultModel(AgentProviderKind.Debug);
var legacyAgents = await dbContext.AgentProfiles
.Where(record =>
(record.ProviderKind != (int)AgentProviderKind.Debug &&
record.ModelName == legacyDebugModel) ||
string.IsNullOrWhiteSpace(record.Description))
.ToListAsync(cancellationToken);
if (legacyAgents.Count == 0)
{
return;
}
foreach (var agent in legacyAgents)
{
var providerKind = (AgentProviderKind)agent.ProviderKind;
if (agent.ProviderKind != (int)AgentProviderKind.Debug &&
agent.ModelName == legacyDebugModel)
{
agent.ModelName = AgentSessionDefaults.GetDefaultModel(providerKind);
AgentSessionServiceLog.LegacyAgentProfileNormalized(logger, agent.Id, providerKind, agent.ModelName);
}
if (string.IsNullOrWhiteSpace(agent.Description))
{
agent.Description = ResolveAgentDescription(string.Empty, agent.SystemPrompt);
}
}
await dbContext.SaveChangesAsync(cancellationToken);
}
private static SessionEntryRecord CreateEntryRecord(
SessionId sessionId,
SessionStreamEntryKind kind,
string author,
string text,
DateTimeOffset timestamp,
AgentProfileId? agentProfileId = null,
string? accentLabel = null)
{
return new SessionEntryRecord
{
Id = Guid.CreateVersion7().ToString("N", System.Globalization.CultureInfo.InvariantCulture),
SessionId = sessionId.Value,
AgentProfileId = agentProfileId?.Value,
Kind = (int)kind,
Author = author,
Text = text,
Timestamp = timestamp,
AccentLabel = accentLabel,
};
}
private static string CreateToolStartText(AgentSessionProviderProfile providerProfile)
{
return providerProfile.Kind == AgentProviderKind.Debug
? "Preparing local debug workflow."
: string.Create(
System.Globalization.CultureInfo.InvariantCulture,
$"Launching {providerProfile.DisplayName} in the local playground.");
}
private static string CreateToolDoneText(AgentSessionProviderProfile providerProfile)
{
return providerProfile.Kind == AgentProviderKind.Debug
? "Debug workflow finished."
: string.Create(
System.Globalization.CultureInfo.InvariantCulture,
$"{providerProfile.DisplayName} turn finished.");
}
private static SessionStreamEntry MapEntry(SessionEntryRecord record)
{
return new SessionStreamEntry(
record.Id,
new SessionId(record.SessionId),
(SessionStreamEntryKind)record.Kind,
record.Author,
record.Text,
record.Timestamp,
record.AgentProfileId is Guid agentProfileId ? new AgentProfileId(agentProfileId) : null,
record.AccentLabel);
}