forked from PowerShell/AIShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShell.cs
More file actions
762 lines (659 loc) · 25.1 KB
/
Shell.cs
File metadata and controls
762 lines (659 loc) · 25.1 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
using System.Reflection;
using System.Text;
using AIShell.Abstraction;
using AIShell.Kernel.Commands;
using AIShell.Kernel.Mcp;
using Microsoft.Extensions.AI;
using Microsoft.PowerShell;
using Spectre.Console;
namespace AIShell.Kernel;
internal sealed class Shell : IShell
{
private readonly bool _isInteractive;
private readonly string _version;
private readonly List<LLMAgent> _agents;
private readonly ShellWrapper _wrapper;
private readonly HashSet<string> _textToIgnore;
private readonly Setting _setting;
private readonly McpManager _mcpManager;
private bool _shouldRefresh;
private LLMAgent _activeAgent;
private CancellationTokenSource _cancellationSource;
/// <summary>
/// Indicates if we want to exit the shell.
/// </summary>
internal bool Exit { set; get; }
/// <summary>
/// Indicates if we want to regenerate for the last query.
/// </summary>
internal bool Regenerate { set; get; }
/// <summary>
/// The last query sent by user.
/// </summary>
internal string LastQuery { private set; get; }
/// <summary>
/// The agent that served the last query.
/// </summary>
internal LLMAgent LastAgent { private set; get; }
/// <summary>
/// Gets the host.
/// </summary>
internal Host Host { get; }
/// <summary>
/// Gets the command runner.
/// </summary>
internal CommandRunner CommandRunner { get; }
/// <summary>
/// Gets the channel to the command-line shell.
/// </summary>
internal Channel Channel { get; }
/// <summary>
/// Gets the event handler that will be set when initialization is done.
/// </summary>
internal ManualResetEvent InitEventHandler { get; }
/// <summary>
/// Gets the agent list.
/// </summary>
internal List<LLMAgent> Agents => _agents;
/// <summary>
/// Gets the cancellation token.
/// </summary>
internal CancellationToken CancellationToken => _cancellationSource.Token;
/// <summary>
/// Gets the currently active agent.
/// </summary>
internal LLMAgent ActiveAgent => _activeAgent;
/// <summary>
/// Gets the version from the assembly attribute.
/// </summary>
internal string Version => _version;
/// <summary>
/// Gets the MCP manager.
/// </summary>
internal McpManager McpManager => _mcpManager;
#region IShell implementation
IHost IShell.Host => Host;
bool IShell.ChannelEstablished => Channel is not null;
CancellationToken IShell.CancellationToken => _cancellationSource.Token;
List<CodeBlock> IShell.ExtractCodeBlocks(string text, out List<SourceInfo> sourceInfos) => Utils.ExtractCodeBlocks(text, out sourceInfos);
async Task<List<AIFunction>> IShell.GetAIFunctions() => await _mcpManager.ListAvailableTools();
async Task<FunctionResultContent> IShell.CallAIFunction(FunctionCallContent functionCall, bool captureException, bool includeDetailedErrors, CancellationToken cancellationToken)
=> await _mcpManager.CallToolAsync(functionCall, captureException, includeDetailedErrors, cancellationToken);
#endregion IShell implementation
/// <summary>
/// Creates an instance of <see cref="Shell"/>.
/// </summary>
internal Shell(bool interactive, ShellArgs args)
{
_isInteractive = interactive;
_wrapper = args.ShellWrapper;
// Create the channel if the args is specified.
// The channel object starts the connection initialization on a background thread,
// to run in parallel with the rest of the Shell initialization.
InitEventHandler = new ManualResetEvent(false);
Channel = args.Channel is null ? null : new Channel(args.Channel, this);
_agents = [];
_activeAgent = null;
_shouldRefresh = false;
_setting = Setting.Load();
_textToIgnore = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
_cancellationSource = new CancellationTokenSource();
_version = typeof(Shell).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
_mcpManager = new(this);
Exit = false;
Regenerate = false;
LastQuery = null;
LastAgent = null;
Host = new Host();
if (interactive)
{
ShowBanner();
CommandRunner = new CommandRunner(this);
SetReadLineExperience();
}
LoadAvailableAgents();
Console.CancelKeyPress += OnCancelKeyPress;
InitEventHandler.Set();
if (interactive)
{
ShowLandingPage();
}
Telemetry.TrackSession(standalone: Channel is null);
}
internal void ShowBanner()
{
string banner = _wrapper?.Banner is null ? "AI Shell" : _wrapper.Banner;
string version = _wrapper?.Version is null ? _version : _wrapper.Version;
// The color '#7a7a7a' is most close to 'grey' but with high enough contrast to pass the contrast checker.
Host.MarkupLine($"[bold]{banner.EscapeMarkup()}[/]")
.MarkupLine($"[#7a7a7a]{version.EscapeMarkup()}[/]")
.WriteLine();
}
internal void ShowLandingPage()
{
// Write out information about the active agent.
if (_activeAgent is not null)
{
bool isWrapped = true;
var impl = _activeAgent.Impl;
if (!impl.Name.Equals(_wrapper?.Agent, StringComparison.OrdinalIgnoreCase))
{
isWrapped = false;
Host.MarkupLine($"Using the agent [green]{impl.Name}[/]:");
}
_activeAgent.Display(Host, isWrapped ? _wrapper.Description : null);
}
try
{
McpConfig config = _mcpManager.ParseMcpJsonTask.GetAwaiter().GetResult();
if (config is { Servers.Count: > 0 })
{
Host.MarkupNoteLine($"{config.Servers.Count} MCP server(s) configured. Run {Formatter.Command("/mcp")} for details.");
}
}
catch (Exception e)
{
Host.WriteErrorLine($"Failed to load the 'mcp.json' file:\n{e.Message}\nRun '/mcp config' to open the 'mcp.json' file.\n");
}
// Write out help.
Host.MarkupLine($"Run {Formatter.Command("/help")} for more instructions.\n");
}
/// <summary>
/// Get all code blocks from the last LLM response.
/// </summary>
/// <returns></returns>
internal List<CodeBlock> GetCodeBlockFromLastResponse()
{
return Host.MarkdownRender.GetAllCodeBlocks();
}
internal void OnUserAction(UserActionPayload actionPayload)
{
if (actionPayload.Action is UserAction.CodeCopy)
{
var codePayload = (CodePayload)actionPayload;
_textToIgnore.Add(codePayload.Code);
}
if (LastAgent.Impl.CanAcceptFeedback(actionPayload.Action))
{
var state = Tuple.Create(LastAgent.Impl, actionPayload);
ThreadPool.QueueUserWorkItem(
callBack: static tuple => tuple.Item1.OnUserAction(tuple.Item2),
state: state,
preferLocal: false);
}
}
/// <summary>
/// Load a plugin assembly file and process the agents defined in it.
/// </summary>
internal void ProcessAgentPlugin(string pluginName, string pluginDir, string pluginFile)
{
AgentAssemblyLoadContext context = new(pluginName, pluginDir);
Assembly plugin = context.LoadFromAssemblyPath(pluginFile);
foreach (Type type in plugin.ExportedTypes)
{
if (!typeof(ILLMAgent).IsAssignableFrom(type))
{
continue;
}
var agent = (ILLMAgent)Activator.CreateInstance(type);
var agentHome = Path.Join(Utils.AgentConfigHome, agent.Name);
var config = new AgentConfig
{
IsInteractive = _isInteractive,
ConfigurationRoot = Directory.CreateDirectory(agentHome).FullName,
RenderingStyle = Console.IsOutputRedirected
? RenderingStyle.FullResponsePreferred
: RenderingStyle.StreamingResponsePreferred,
Context = agent.Name.Equals(_wrapper?.Agent, StringComparison.OrdinalIgnoreCase)
? _wrapper.Context
: null
};
agent.Initialize(config);
_agents.Add(new LLMAgent(agent, context));
}
}
/// <summary>
/// Load all available agents.
/// </summary>
private void LoadAvailableAgents()
{
string inboxAgentHome = Path.Join(AppContext.BaseDirectory, "agents");
IEnumerable<string> agentDirs = Enumerable.Concat(
Directory.EnumerateDirectories(inboxAgentHome),
Directory.EnumerateDirectories(Utils.AgentHome));
foreach (string dir in agentDirs)
{
string name = Path.GetFileName(dir);
string file = Path.Join(dir, $"{name}.dll");
if (!File.Exists(file))
{
continue;
}
try
{
ProcessAgentPlugin(name, dir, file);
}
catch (Exception ex)
{
Host.WriteErrorLine($"Failed to load the agent '{name}': {ex.Message}\n");
}
}
if (_agents.Count is 0)
{
Host.MarkupWarningLine($"No agent available.\n");
return;
}
try
{
LLMAgent chosenAgent = null;
string active = _wrapper?.Agent ?? _setting.DefaultAgent;
if (!string.IsNullOrEmpty(active))
{
foreach (LLMAgent agent in _agents)
{
if (agent.Impl.Name.Equals(active, StringComparison.OrdinalIgnoreCase))
{
chosenAgent = agent;
break;
}
}
if (chosenAgent is null)
{
Host.MarkupWarningLine($"The configured active agent '{active}' is not available.\n");
}
else if (_wrapper?.Prompt is not null)
{
chosenAgent.Prompt = _wrapper.Prompt;
}
}
// If there is only 1 agent available, use it as the active one.
// Otherwise, ask user to choose the active one from the list.
chosenAgent ??= _agents.Count is 1
? _agents[0]
: Host.PromptForSelectionAsync(
title: "Welcome to AI Shell! We’re excited to have you explore our [bold]Public Preview[/]. Documentation is available at [link=https://aka.ms/AIShell-Docs]aka.ms/AIShell-Docs[/], and we’d love to hear your thoughts - share your feedback with us at [link=https://aka.ms/AIShell-Feedback]aka.ms/AIShell-Feedback[/].\n\n[orange1]Please select an AI [Blue]agent[/] to use[/]:\n[#7a7a7a](You can switch to another agent later by typing [Blue]@<agent name>[/])[/]",
choices: _agents,
converter: static a => a.Impl.Name)
.GetAwaiter().GetResult();
_activeAgent = chosenAgent;
_shouldRefresh = true;
if (_isInteractive)
{
ILLMAgent impl = chosenAgent.Impl;
CommandRunner.LoadCommands(impl.GetCommands(), impl.Name);
}
}
catch (Exception)
{
// Ignore failure from showing the confirmation prompt.
}
}
/// <summary>
/// Switch and use another agent as the active.
/// </summary>
internal void SwitchActiveAgent(LLMAgent agent)
{
ILLMAgent impl = agent.Impl;
if (_activeAgent is null)
{
_activeAgent = agent;
_shouldRefresh = true;
CommandRunner.LoadCommands(impl.GetCommands(), impl.Name);
}
else if (_activeAgent != agent)
{
_activeAgent = agent;
_shouldRefresh = true;
CommandRunner.UnloadAgentCommands();
CommandRunner.LoadCommands(impl.GetCommands(), impl.Name);
}
}
/// <summary>
/// For reference:
/// https://github.com/dotnet/command-line-api/blob/67df30a1ac4152e7f6278847b88b8f1ea1492ba7/src/System.CommandLine/Invocation/ProcessTerminationHandler.cs#L73
/// TODO: We may want to implement `OnPosixSignal` too for more reliable cancellation on non-Windows.
/// </summary>
private void OnCancelKeyPress(object sender, ConsoleCancelEventArgs args)
{
// Set the Cancel property to true to prevent the process from terminating.
args.Cancel = true;
switch (args.SpecialKey)
{
// Treat both Ctrl-C and Ctrl-Break as the same.
case ConsoleSpecialKey.ControlC:
case ConsoleSpecialKey.ControlBreak:
// Request cancellation and refresh the cancellation source.
_cancellationSource.Cancel();
_cancellationSource = new CancellationTokenSource();
return;
}
}
/// <summary>
/// Configure the read-line experience.
/// </summary>
private void SetReadLineExperience()
{
Utils.SetDefaultKeyHandlers();
ReadLineHelper helper = new(this, CommandRunner);
PSConsoleReadLine.GetOptions().ReadLineHelper = helper;
}
/// <summary>
/// Execute a command.
/// </summary>
/// <param name="input">Command line to be executed.</param>
private void RunCommand(string input)
{
string commandLine = input[1..].Trim();
if (commandLine == string.Empty)
{
Host.WriteErrorLine("Command is missing.");
return;
}
try
{
CommandRunner.InvokeCommand(commandLine);
}
catch (Exception e)
{
Host.WriteErrorLine(e.Message);
}
}
private string TaggingAgent(string input, ref LLMAgent agent)
{
input = input.TrimEnd();
int index = input.IndexOf(' ');
string targetName = index is -1 ? input[1..] : input[1..index];
if (string.IsNullOrEmpty(targetName))
{
Host.WriteErrorLine("No target agent specified after '@'.");
return null;
}
if (_agents.Count is 0)
{
Host.WriteErrorLine("No agent is available.");
return null;
}
LLMAgent targetAgent = AgentCommand.FindAgent(targetName, this);
if (targetAgent is null)
{
AgentCommand.AgentNotFound(targetName, this);
return null;
}
agent = targetAgent;
SwitchActiveAgent(targetAgent);
if (index is -1)
{
// Display the landing page when there is no query following the tagging.
Host.MarkupLine($"Using the agent [green]{targetAgent.Impl.Name}[/]:");
targetAgent.Display(Host);
return null;
}
return input[index..].TrimStart();
}
private void IgnoreStaleClipboardContent()
{
string copiedText = Clipboard.GetText().Trim();
if (!string.IsNullOrEmpty(copiedText))
{
_textToIgnore.Add(copiedText);
}
}
private async Task<string> GetClipboardContent(string input)
{
if (!_setting.UseClipboardContent)
{
// Skip it when this feature is disabled.
return null;
}
string copiedText = Clipboard.GetText().Trim();
if (string.IsNullOrEmpty(copiedText) || _textToIgnore.Contains(copiedText))
{
return null;
}
// Always avoid asking for the same copied text.
_textToIgnore.Add(copiedText);
if (input.Contains(copiedText))
{
return null;
}
// If clipboard content was copied from the code from the last response (whole or partial)
// by mouse clicking, we should ignore it and don't show the prompt.
if (GetCodeBlockFromLastResponse() is List<CodeBlock> codeBlocks)
{
foreach (CodeBlock code in codeBlocks)
{
if (Utils.Contains(code.Code, copiedText))
{
return null;
}
}
}
string textToShow = copiedText;
if (copiedText.Length > 150)
{
int index = 149;
while (index < copiedText.Length && !char.IsWhiteSpace(copiedText[index]))
{
index++;
}
textToShow = copiedText[..index].TrimEnd() + " <more...>";
}
Host.RenderReferenceText("clipboard content", textToShow);
bool confirmed = await Host.PromptForConfirmationAsync(
prompt: "Include the clipboard content as context information for your query?",
defaultValue: true);
return confirmed ? copiedText : null;
}
private string GetOneRemoteQuery(out CancellationToken readlineCancelToken)
{
readlineCancelToken = CancellationToken.None;
if (Channel is null)
{
return null;
}
lock (Channel)
{
if (Channel.TryDequeueQuery(out string remoteQuery))
{
return remoteQuery;
}
readlineCancelToken = Channel.ReadLineCancellationToken;
return null;
}
}
private async Task<string> ReadUserInput(string prompt, CancellationToken cancellationToken)
{
string newLine = Console.CursorLeft is 0 ? string.Empty : "\n";
Host.Markup($"{newLine}[bold green]{prompt}[/]> ");
string input = PSConsoleReadLine.ReadLine(cancellationToken);
if (string.IsNullOrEmpty(input))
{
return null;
}
if (!input.Contains(' '))
{
foreach (var name in CommandRunner.Commands.Keys)
{
if (string.Equals(input, name, StringComparison.OrdinalIgnoreCase))
{
string command = $"/{name}";
bool confirmed = await Host.PromptForConfirmationAsync(
$"Do you mean to run the command {Formatter.Command(command)} instead?",
defaultValue: true,
cancellationToken: CancellationToken.None);
if (confirmed)
{
input = command;
}
break;
}
}
}
return input;
}
/// <summary>
/// Give an agent the opportunity to refresh its chat session, in the unforced way.
/// </summary>
private async Task RefreshChatAsNeeded(LLMAgent agent)
{
if (_shouldRefresh)
{
_shouldRefresh = false;
await agent?.Impl.RefreshChatAsync(this, force: false);
}
}
/// <summary>
/// Run a chat REPL.
/// </summary>
internal async Task RunREPLAsync()
{
IgnoreStaleClipboardContent();
while (!Exit)
{
string input = null;
bool isRemoteQuery = false;
LLMAgent agent = _activeAgent;
try
{
await RefreshChatAsNeeded(agent);
if (Regenerate)
{
input = LastQuery;
Regenerate = false;
}
else
{
input = GetOneRemoteQuery(out CancellationToken readlineCancelToken);
if (input is not null)
{
// Write out the remote query, in the same style as user typing.
Host.Markup($"\n>> Remote Query Received:\n");
Host.MarkupLine($"[teal]{input.EscapeMarkup()}[/]");
isRemoteQuery = true;
}
else
{
input = await ReadUserInput(agent?.Prompt ?? Utils.DefaultPrompt, readlineCancelToken);
if (input is null)
{
continue;
}
}
}
if (input.StartsWith('/'))
{
RunCommand(input);
continue;
}
if (input.StartsWith('@'))
{
input = TaggingAgent(input, ref agent);
if (input is null)
{
continue;
}
else
{
// We may be switching to an agent that hasn't setup its chat session yet.
// So, give it a chance to do so before calling its 'Chat' method.
await RefreshChatAsNeeded(agent);
}
}
string copiedText = await GetClipboardContent(input);
if (copiedText is not null)
{
input = string.Concat(input, "\n\n", copiedText);
}
// Now it's a query to the LLM.
if (agent is null)
{
// No agent to serve the query. Print the warning and go back to read-line prompt.
string agentCommand = Formatter.Command($"/agent use");
string helpCommand = Formatter.Command("/help");
Host.WriteLine()
.MarkupWarningLine("No active agent selected, chat is disabled.")
.MarkupWarningLine($"Run {agentCommand} to select an agent, or {helpCommand} for more instructions.")
.WriteLine();
continue;
}
try
{
LastQuery = input;
LastAgent = agent;
// TODO: Consider `WaitAsync(CancellationToken)` to handle an agent not responding to ctr+c.
// One problem to use `WaitAsync` is to make sure we give reasonable time for the agent to handle the cancellation.
bool wasQueryServed = await agent.Impl.ChatAsync(input, this);
if (!wasQueryServed)
{
Host.WriteLine()
.MarkupWarningLine($"[[{Utils.AppName}]]: Agent self-check failed. Resolve the issue as instructed and try again.")
.MarkupWarningLine($"[[{Utils.AppName}]]: Run {Formatter.Command($"/agent config {agent.Impl.Name}")} to edit the settings for the agent.");
}
Telemetry.TrackQuery(agent.Impl.Name, isRemoteQuery);
}
catch (Exception ex)
{
if (ex is OperationCanceledException)
{
// User cancelled the operation, so we return to the read-line prompt.
continue;
}
StringBuilder sb = null;
string message = ex.Message;
string stackTrace = ex.StackTrace;
while (ex.InnerException is { })
{
sb ??= new(message, capacity: message.Length * 3);
if (sb[^1] is not '\n')
{
sb.Append('\n');
}
sb.Append($" Inner -> {ex.InnerException.Message}");
ex = ex.InnerException;
}
if (sb is not null)
{
message = sb.ToString();
}
string separator = message.EndsWith('\n') ? "\n" : "\n\n";
Host.WriteErrorLine()
.WriteErrorLine($"Agent failed to generate a response: {message}{separator}{stackTrace}")
.WriteErrorLine();
}
}
catch (Exception e)
{
Host.WriteErrorLine()
.WriteErrorLine($"{e.Message}\n{e.StackTrace}")
.WriteErrorLine();
}
}
}
/// <summary>
/// Run a one-time chat.
/// </summary>
/// <param name="prompt"></param>
internal async Task RunOnceAsync(string prompt)
{
if (_activeAgent is null)
{
Host.WriteErrorLine("No active agent was configured.");
Host.WriteErrorLine($"Run '{Utils.AppName} --settings' to configure the active agent. Run '{Utils.AppName} --help' for details.");
return;
}
try
{
await _activeAgent.Impl.RefreshChatAsync(this, force: false);
await _activeAgent.Impl.ChatAsync(prompt, this);
Telemetry.TrackQuery(_activeAgent.Impl.Name, isRemote: false);
}
catch (OperationCanceledException)
{
Host.WriteErrorLine("Operation was aborted.");
}
catch (Exception e)
{
Host.WriteErrorLine(e.Message);
}
}
}