-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathProgram.cs
More file actions
567 lines (463 loc) · 23.9 KB
/
Copy pathProgram.cs
File metadata and controls
567 lines (463 loc) · 23.9 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
using GTerm.Extensions;
using GTerm.Listeners;
using GTerm.MCP;
using Spectre.Console;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
namespace GTerm
{
class Program
{
private const string HEADER = @"
██████ ████████ ███████ ██████ ███ ███
██ ██ ██ ██ ██ ████ ████
██ ███ ██ █████ ██████ ██ ████ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██████ ██ ███████ ██ ██ ██ ██
";
private static readonly object Locker = new();
private static readonly StringBuilder LogBuffer = new();
private static readonly StringBuilder MarkupBuffer = new();
private static readonly StringBuilder InputBuffer = new();
private static readonly Thread UserInputThread = new(ProcessUserInput);
private static readonly ILogListener Listener = new TcpLogListener();
private static string ArchivePath = string.Empty;
private static Config Config = new();
private static WebSocketAPI? API;
private static CommandCollector? Collector;
private static MCPServer? MCP;
static void Main(string[] args)
{
LocalLogger.WriteLine("Starting up...");
// prevent running it multiple times
Process curProc = Process.GetCurrentProcess();
string processName = curProc.ProcessName;
if (Process.GetProcesses().Count(p => p.ProcessName == processName) > 1)
{
LocalLogger.WriteLine("Another instance of GTerm is running, aborting");
return;
}
Console.Clear();
Console.Title = "GTerm";
Config = new Config(args);
Process? parent = curProc.GetParent();
LocalLogger.WriteLine($"Parent process: {parent?.ProcessName}");
if (parent?.ProcessName.Equals("gmod", StringComparison.OrdinalIgnoreCase) == true)
{
LocalLogger.WriteLine("Started from Gmod!");
Config.StartAsGmod = false; // this cannot be true if gmod already runs GTerm as a child process
if (Config.MonitorGmod)
{
LocalLogger.WriteLine("Gmod monitoring starting");
parent.EnableRaisingEvents = true;
parent.Exited += (_, __) =>
{
if (parent.ExitCode == 0) return;
LocalLogger.WriteLine("Gmod crashed, attempting to restart!");
ProcessStartInfo oldStartInfo = parent.StartInfo;
if (GmodInterop.TryGetGmodPath(out string gmodBinpath))
{
oldStartInfo.FileName = gmodBinpath;
LocalLogger.WriteLine("Restarting Gmod!");
Process.Start(parent.StartInfo); // reboot gmod because crash and it was the owning process
curProc.Kill(); // we also kill the current process, because its likely it will be rebooted from gmod
}
};
}
}
string? processPath = Path.GetDirectoryName(Process.GetCurrentProcess().GetExecutablePath());
if (processPath != null)
{
ArchivePath = Path.Combine(processPath, "Archives");
if (Config.ArchiveLogs)
{
if (!Directory.Exists(ArchivePath))
{
LocalLogger.WriteLine("Archives directory was not found, creating it at: ", ArchivePath);
Directory.CreateDirectory(ArchivePath);
}
}
}
Task.Run(GmodInterop.InstallGTerm); // try to install the gterm module
if (Config.StartAsGmod)
{
if (!GmodInterop.StartGmod()) return;
}
ShowWaitingConnection();
Listener.OnConnected += (_, __) =>
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(new string('=', Console.BufferWidth - 1));
Console.WriteLine(HEADER);
Console.WriteLine(new string('=', Console.BufferWidth - 1));
Console.WriteLine("Welcome to GTerm! You can read your Garry's Mod logs from here in real-time.");
Console.WriteLine("You can also execute any command you normally would by typing here!");
Console.WriteLine();
Console.WriteLine();
Console.Write("If you have any issue with GTerm please open an issue at: ");
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine("https://github.com/Earu/GTerm/issues");
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Enjoy your stay!");
Console.Write("\n\n\n");
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
};
Listener.OnDisconnected += (_, __) =>
{
AnsiConsole.Markup("[bold red]Disconnected[/]");
ShowWaitingConnection();
};
Listener.OnLog += OnLog;
Listener.OnError += OnError;
Listener.Start();
UserInputThread.Start();
if (Config.API)
{
API = new WebSocketAPI(Listener, Config.APIPort, Config.APISecret);
Task.Run(API.StartAsync);
}
if (Config.MCP)
{
Collector = new CommandCollector(Listener, Config.MCPCollectionWindowMs);
MCP = new MCPServer(Collector, Listener, Config.MCPPort, Config.MCPSecret);
Task.Run(() => MCP.StartAsync());
}
}
private static void ProcessUserInput()
{
Console.WriteLine(); // on UNIX this prevents a terminal deadlock
while (true)
{
if (!Console.KeyAvailable) {
Thread.Sleep(100);
continue;
}
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
// An open consent prompt owns the keyboard: nothing reaches the game or the input line.
if (ConsentPrompt.HandleKey(keyInfo)) continue;
switch (keyInfo.Key)
{
case ConsoleKey.Enter:
{
string input = InputBuffer.ToString();
InputBuffer.Clear();
if (string.IsNullOrWhiteSpace(input.Trim())) continue;
if (input.Trim().Equals("clear", StringComparison.CurrentCultureIgnoreCase))
Console.Clear();
// GTerm's own command: review and enable tool packages without an agent.
if (input.Trim().Equals("packages", StringComparison.CurrentCultureIgnoreCase))
{
if (MCP == null) WriteNotice("packages: the MCP server is disabled (Config.json \"MCP\")");
else _ = MCP.RequestPackagesFromConsoleAsync();
Console.CursorLeft = 0;
Console.Write(new string(' ', Console.BufferWidth - 1));
break;
}
_ = Listener.WriteMessage(input);
Console.CursorLeft = 0;
Console.Write(new string(' ', Console.BufferWidth - 1));
}
break;
case ConsoleKey.Backspace:
if (InputBuffer.Length > 0)
InputBuffer.Remove(InputBuffer.Length - 1, 1);
int oldCursorLeft = Console.CursorLeft;
int oldCursorTop = Console.CursorTop;
Console.CursorLeft = 0;
Console.Write(new string(' ', Console.BufferWidth - 1));
Console.CursorLeft = oldCursorLeft;
Console.CursorTop = oldCursorTop;
break;
case ConsoleKey.Escape:
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
IntPtr hWndConsole = Win32Extensions.GetConsoleWindow();
Win32Extensions.ShowWindow(hWndConsole, Win32Extensions.SW_MINIMIZE);
}
break;
default:
InputBuffer.Append(keyInfo.KeyChar);
if (InputBuffer.Length > 255) // source console is limited to 255 characters
InputBuffer.Remove(254, InputBuffer.Length - 255);
break;
}
Console.Write("\r" + InputLine());
}
}
private static string InputLine() => InputBuffer.ToString();
private static void ShowWaitingConnection() => AnsiConsole.Status()
.AutoRefresh(false)
.Spinner(Spinner.Known.Aesthetic)
.SpinnerStyle(Style.Parse("red bold"))
.StartAsync("Waiting for Garry's Mod connection...", async ctx =>
{
while (true)
{
if (Listener.IsConnected)
{
ctx.Status = "Connected";
ctx.SpinnerStyle(Style.Parse("green cold"));
ctx.Spinner(Spinner.Known.Star);
}
ctx.Refresh();
await Task.Delay(500);
}
});
/// <summary>
/// Shows what an MCP agent just did, in GTerm's own console.
///
/// An MCP client displays the tool name but usually not the arguments, so from the chat window
/// alone you cannot tell which command or which Lua an agent pushed into your game. GTerm is
/// already the window you watch the console in, so it is the honest place to surface this, and
/// unlike the client it has no truncation or rendering rules to work around.
///
/// Routed through OnLog so it inherits the cursor handling that keeps typing stable, plus the
/// archiving and API fan-out that game output gets.
/// </summary>
internal enum AgentDetail
{
/// <summary>Short and inert (a path, a rectangle): sits on the header line, uncoloured.</summary>
Plain,
/// <summary>A console command: stays on the header line, but highlighted.</summary>
Command,
/// <summary>Lua: gets its own lines under the header, since a snippet tacked onto a header is unreadable.</summary>
Lua,
/// <summary>A short Lua expression (a package tool's args table): stays on the header line, highlighted.</summary>
LuaInline,
}
/// <param name="realm">
/// The Lua state the call touches, shown as a colour block in the wiki's own realm colours.
/// Null for calls that touch no realm at all (a disk read, a console command), which then get
/// no block: reserving it for realms is what makes it mean something.
/// </param>
internal static void WriteAgentAction(string tool, string? detail, AgentDetail kind = AgentDetail.Plain, string? realm = null)
{
bool hasRealm = !string.IsNullOrWhiteSpace(realm);
string label = hasRealm ? $"█ {realm!.ToUpperInvariant(),-6} " : string.Empty;
string head = $"[agent] {label}{tool}";
string headMarkup = $"[bold magenta1]{Markup.Escape("[agent]")}[/] "
+ (hasRealm ? $"[{SyntaxHighlighter.RealmColour(realm)}]{Markup.Escape(label)}[/]" : string.Empty)
+ $"[bold magenta1]{Markup.Escape(tool)}[/]";
if (string.IsNullOrWhiteSpace(detail) || kind == AgentDetail.Lua)
{
WriteAgentLine(head, headMarkup);
if (kind == AgentDetail.Lua && !string.IsNullOrWhiteSpace(detail))
{
foreach (string line in detail.Replace("\r", string.Empty).Split('\n'))
WriteAgentLine(line, SyntaxHighlighter.Lua(line));
}
return;
}
string tail = kind switch
{
AgentDetail.Command => SyntaxHighlighter.ConsoleCommand(detail),
AgentDetail.LuaInline => SyntaxHighlighter.Lua(detail),
_ => Markup.Escape(detail),
};
WriteAgentLine($"{head} {detail}", $"{headMarkup} {tail}");
}
/// <summary>A plain line from GTerm itself (notices), in GTerm's own colour.</summary>
internal static void WriteNotice(string plain, string? markup = null)
=> WriteAgentLine(plain, markup ?? $"[magenta1]{Markup.Escape(plain)}[/]");
/// <summary>
/// Draws (or redraws in place) a block of GTerm's own lines at the bottom of the console.
/// <paramref name="previousRows"/> is what the last draw returned; the cursor is moved back
/// up over it so the block replaces itself. Returns the rows this draw occupied. Only used
/// while a consent prompt holds all other output, so nothing else moves the cursor.
/// </summary>
internal static int RenderBlock(IReadOnlyList<(string plain, string markup)> lines, int previousRows)
{
lock (Locker)
{
StringBuilder sb = new();
if (previousRows > 0) sb.Append("\x1b[").Append(previousRows).Append('A');
int rows = 0;
foreach ((string plain, string markup) in lines)
{
sb.Append("\r\x1b[2K");
try { sb.Append(AnsiConsole.Console.Profile.Capabilities.Ansi ? MarkupToAnsi(markup) : plain); }
catch { sb.Append(plain); }
sb.Append('\n');
rows += WrappedRowCount(plain);
}
// Clear the input line the block scrolled past, then leave the cursor on it.
sb.Append("\r\x1b[2K");
Console.Write(sb.ToString());
Console.Out.Flush();
return rows;
}
}
private static string MarkupToAnsi(string markup)
{
if (markup.Length == 0) return string.Empty;
StringWriter writer = new();
IAnsiConsole console = AnsiConsole.Create(new AnsiConsoleSettings
{
Ansi = AnsiSupport.Yes,
ColorSystem = ColorSystemSupport.Detect,
Out = new AnsiConsoleOutput(writer),
});
console.Markup(markup);
return writer.ToString();
}
/// <summary>One console line of GTerm's own, carrying its own colours rather than the flat tint game output gets.</summary>
private static void WriteAgentLine(string plain, string markup)
=> OnLog(null!, new LogEventArgs(0, 0, "gterm", AgentActionColor, $"{plain}\n") { MarkupOverride = $"{markup}\n" });
private static readonly System.Drawing.Color AgentActionColor = System.Drawing.Color.FromArgb(255, 0, 255);
private static void OnError(object sender, ErrorEventArgs e)
{
string stackTrace = SanitizeLogMessage(e.GetException().ToString());
AnsiConsole.Markup($"[italic red]{stackTrace}[/]");
}
/// <summary>
/// How many terminal rows a line will occupy once the window wraps it. Measured on the plain
/// text, never the markup, since colour tags take no visible width.
/// </summary>
private static int WrappedRowCount(string line)
{
int width;
try { width = Console.WindowWidth; }
catch { return 1; } // no real console attached (redirected output)
if (width <= 0) return 1;
int visible = line.TrimEnd('\r', '\n').Length;
return Math.Max(1, (visible + width - 1) / width);
}
private static bool IsBlack(System.Drawing.Color col)
=> col.R == 0 && col.G == 0 && col.B == 0;
private static string SanitizeLogMessage(string msg)
{
msg = Markup.Escape(msg);
return msg;
}
private static bool ShouldExcludeLog(string log)
{
if (Config == null) return false;
foreach (Regex pattern in Config.ExclusionPatterns)
{
if (pattern.IsMatch(log)) return true;
}
return false;
}
/// <summary>Game output parked while a consent prompt is open, so the question stays on screen.</summary>
private static readonly Queue<LogEventArgs> HeldLogs = new();
private const int MaxHeldLogs = 5000;
private static int DroppedHeldLogs;
/// <summary>Prints whatever was parked during a prompt. Called when the prompt closes.</summary>
internal static void ReleaseHeldLogs()
{
List<LogEventArgs> backlog;
int dropped;
lock (Locker)
{
if (HeldLogs.Count == 0 && DroppedHeldLogs == 0) return;
backlog = [.. HeldLogs];
HeldLogs.Clear();
dropped = DroppedHeldLogs;
DroppedHeldLogs = 0;
}
WriteNotice($"packages: showing {backlog.Count} line(s) held while the prompt was open{(dropped > 0 ? $" ({dropped} older lines dropped)" : "")}");
foreach (LogEventArgs held in backlog) OnLog(null!, held);
}
private static void OnLog(object sender, LogEventArgs args)
{
lock (Locker)
{
// The prompt owns the screen: everything else waits for the answer.
if (ConsentPrompt.IsOpen)
{
if (HeldLogs.Count >= MaxHeldLogs)
{
HeldLogs.Dequeue();
DroppedHeldLogs++;
}
HeldLogs.Enqueue(args);
return;
}
DateTime now = DateTime.Now;
string timeStamp = now.ToString("hh:mm:ss");
System.Drawing.Color col = IsBlack(args.Color) ? System.Drawing.Color.White : args.Color;
string msg = args.Message;
int newLineIndex = msg.IndexOf('\n');
while (newLineIndex != -1)
{
if (MarkupBuffer.Length == 0 && LogBuffer.Length == 0)
{
MarkupBuffer.Append($"[#ffaf00]{timeStamp}[/] | ");
LogBuffer.Append($"{timeStamp} | ");
API?.StartData(now);
}
string chunk = string.Concat(msg.AsSpan(0, newLineIndex), "\n");
string nextChunk = msg.Length > newLineIndex + 1 ? msg[chunk.Length..] : string.Empty;
LogBuffer.Append(chunk);
MarkupBuffer.Append(args.MarkupOverride ?? $"[rgb({col.R},{col.G},{col.B})]{SanitizeLogMessage(chunk)}[/]");
API?.AppendData(col, chunk);
string mk = MarkupBuffer.ToString();
string log = LogBuffer.ToString();
MarkupBuffer.Clear();
LogBuffer.Clear();
API?.FinishDataAsync();
string logChunk = log.Contains('|', StringComparison.CurrentCulture) ? string.Join("|", log.Split('|').Skip(1).ToArray()) : log; // there should always be 1
if (args.MarkupOverride != null || !string.IsNullOrWhiteSpace(logChunk))
{
// GTerm's own probe/result markers are plumbing, not console output.
if (GTermSentinels.IsSentinel(logChunk)) return;
if (ShouldExcludeLog(logChunk)) return;
int currentTopCursor = Console.CursorTop;
int currentLeftCursor = Console.CursorLeft;
// A line wider than the window wraps onto several rows. Everything below has to
// account for that, or the next line gets written back over the middle of this
// one and the wrapped remainder is left orphaned on screen.
int rows = WrappedRowCount(log);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
Console.MoveBufferArea(0, currentTopCursor, Console.WindowWidth, 1, 0, Math.Min(Console.BufferHeight - 1, currentTopCursor + rows));
}
Console.CursorTop = Math.Min(Console.BufferHeight - 1, currentTopCursor);
Console.CursorLeft = 0;
// Markup can only be malformed on GTerm's own highlighted lines (game output is
// escaped), but a throw here happens inside the console lock and would take the
// whole log path down. Losing the colour is an acceptable trade for never that.
try { AnsiConsole.Markup(mk); }
catch { Console.Write(log); }
Console.Out.Flush();
// Where the write actually finished, which already accounts for wrapping and for
// the buffer scrolling. Trust it over arithmetic.
int afterTopCursor = Console.CursorTop;
// this makes typing when the console is filled more stable
if (currentTopCursor + rows >= Console.BufferHeight)
{
Console.Write(InputLine());
}
Console.CursorTop = Math.Min(Console.BufferHeight - 1, afterTopCursor);
Console.CursorLeft = currentLeftCursor;
if (Config.ArchiveLogs)
{
string fileName = $"{DateTime.Now.ToString("d").Replace("/", "_")}.log";
File.AppendAllText(Path.Combine(ArchivePath, fileName), log);
}
}
msg = nextChunk;
newLineIndex = msg.IndexOf('\n');
if (msg.Length == 0) break;
}
if (MarkupBuffer.Length == 0 && LogBuffer.Length == 0)
{
MarkupBuffer.Append($"[#ffaf00]{timeStamp}[/] | ");
LogBuffer.Append($"{timeStamp} | ");
API?.StartData(now);
}
if (msg.Length > 0)
{
LogBuffer.Append(msg);
MarkupBuffer.Append($"[rgb({col.R},{col.G},{col.B})]{SanitizeLogMessage(msg)}[/]");
API?.AppendData(col, msg);
}
}
}
}
}