ft-scout 9.5.6 → 9.5.7

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.
@@ -8,6 +8,7 @@ using System.Windows.Forms;
8
8
  using System.Runtime.InteropServices;
9
9
  using System.Diagnostics;
10
10
  using System.Collections.Generic;
11
+ using System.Reflection;
11
12
 
12
13
  namespace Scout.ComputerControl
13
14
  {
@@ -43,6 +44,9 @@ namespace Scout.ComputerControl
43
44
  [DllImport("user32.dll")]
44
45
  public static extern int GetSystemMetrics(int nIndex);
45
46
 
47
+ [DllImport("user32.dll", SetLastError = true)]
48
+ public static extern bool SetProcessDpiAwarenessContext(IntPtr dpiContext);
49
+
46
50
  [DllImport("user32.dll")]
47
51
  public static extern bool SetProcessDPIAware();
48
52
 
@@ -61,6 +65,15 @@ namespace Scout.ComputerControl
61
65
  [DllImport("user32.dll")]
62
66
  public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
63
67
 
68
+ [DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Auto)]
69
+ public static extern IntPtr ShellExecute(
70
+ IntPtr hwnd,
71
+ string lpOperation,
72
+ string lpFile,
73
+ string lpParameters,
74
+ string lpDirectory,
75
+ int nShowCmd);
76
+
64
77
  [DllImport("user32.dll")]
65
78
  public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
66
79
  public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
@@ -85,6 +98,18 @@ namespace Scout.ComputerControl
85
98
  [DllImport("user32.dll", SetLastError = true)]
86
99
  public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
87
100
 
101
+ [DllImport("user32.dll")]
102
+ public static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
103
+
104
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
105
+ public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
106
+
107
+ [DllImport("user32.dll", CharSet = CharSet.Auto)]
108
+ public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);
109
+
110
+ [DllImport("user32.dll", CharSet = CharSet.Auto)]
111
+ public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, StringBuilder lParam);
112
+
88
113
  [StructLayout(LayoutKind.Sequential)]
89
114
  public struct INPUT
90
115
  {
@@ -133,6 +158,8 @@ namespace Scout.ComputerControl
133
158
  }
134
159
 
135
160
  public const uint WM_CLOSE = 0x0010;
161
+ public const uint WM_SETTEXT = 0x000C;
162
+ public const uint EM_REPLACESEL = 0x00C2;
136
163
  public const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
137
164
  public const uint KEYEVENTF_KEYUP = 0x0002;
138
165
  public const uint KEYEVENTF_UNICODE = 0x0004;
@@ -178,6 +205,7 @@ namespace Scout.ComputerControl
178
205
  public const int SM_CYSCREEN = 1;
179
206
  public const int SM_CXVIRTUALSCREEN = 78;
180
207
  public const int SM_CYVIRTUALSCREEN = 79;
208
+ public const int SW_SHOWNORMAL = 1;
181
209
  public const int SW_SHOW = 5;
182
210
  public const int SW_RESTORE = 9;
183
211
 
@@ -233,7 +261,15 @@ namespace Scout.ComputerControl
233
261
  {
234
262
  try
235
263
  {
236
- SetProcessDPIAware();
264
+ try
265
+ {
266
+ // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4
267
+ SetProcessDpiAwarenessContext((IntPtr)(-4));
268
+ }
269
+ catch
270
+ {
271
+ try { SetProcessDPIAware(); } catch { }
272
+ }
237
273
  IntPtr hwinsta = OpenWindowStation("WinSta0", false, 0x10000000);
238
274
  if (hwinsta != IntPtr.Zero)
239
275
  {
@@ -412,59 +448,81 @@ namespace Scout.ComputerControl
412
448
  return list;
413
449
  }
414
450
 
415
- public static bool FocusWindow(string titleOrApp)
451
+ public static IntPtr FindWindowByApp(string titleOrApp)
416
452
  {
453
+ if (string.IsNullOrEmpty(titleOrApp)) return IntPtr.Zero;
454
+ string target = titleOrApp.ToLower().Trim();
455
+ IntPtr foundHwnd = IntPtr.Zero;
456
+
457
+ // Priority 1: Match process name exactly or without .exe
417
458
  try
418
459
  {
419
- string target = titleOrApp.ToLower().Trim();
420
- IntPtr foundHwnd = IntPtr.Zero;
421
-
422
- // Priority 1: Match process name exactly or without .exe
423
- try
460
+ Process[] procs = Process.GetProcesses();
461
+ foreach (Process p in procs)
424
462
  {
425
- Process[] procs = Process.GetProcesses();
426
- foreach (Process p in procs)
463
+ try
427
464
  {
428
- try
465
+ string pn = p.ProcessName.ToLower();
466
+ if ((pn == target || pn == target + ".exe" || pn.StartsWith(target + ".")) && p.MainWindowHandle != IntPtr.Zero)
429
467
  {
430
- string pn = p.ProcessName.ToLower();
431
- if ((pn == target || pn == target + ".exe" || pn.StartsWith(target + ".")) && p.MainWindowHandle != IntPtr.Zero)
432
- {
433
- foundHwnd = p.MainWindowHandle;
434
- break;
435
- }
468
+ return p.MainWindowHandle;
469
+ }
470
+ bool isBrowserAlias = target == "browser" || target == "web browser" || target == "default browser" || target == "web" || target == "internet" ||
471
+ target.Contains("chrome") || target.Contains("edge") || target.Contains("brave");
472
+ if (isBrowserAlias && (pn == "chrome" || pn == "msedge" || pn == "brave" || pn == "firefox") && p.MainWindowHandle != IntPtr.Zero)
473
+ {
474
+ return p.MainWindowHandle;
436
475
  }
437
- catch { }
438
476
  }
477
+ catch { }
439
478
  }
440
- catch { }
479
+ }
480
+ catch { }
441
481
 
442
- // Priority 2: EnumWindows matching process name or window title
443
- if (foundHwnd == IntPtr.Zero)
482
+ // Priority 2: EnumWindows matching process name or window title
483
+ EnumWindows((hWnd, lParam) =>
484
+ {
485
+ if (IsWindowVisible(hWnd))
444
486
  {
445
- EnumWindows((hWnd, lParam) =>
487
+ StringBuilder sb = new StringBuilder(512);
488
+ GetWindowText(hWnd, sb, sb.Capacity);
489
+ string t = sb.ToString().Trim().ToLower();
490
+
491
+ // Skip empty or system helper window titles
492
+ if (string.IsNullOrEmpty(t) || t == "default ime" || t == "msctfime ui")
446
493
  {
447
- if (IsWindowVisible(hWnd))
448
- {
449
- StringBuilder sb = new StringBuilder(512);
450
- GetWindowText(hWnd, sb, sb.Capacity);
451
- string t = sb.ToString().Trim().ToLower();
494
+ return true;
495
+ }
452
496
 
453
- uint pid;
454
- GetWindowThreadProcessId(hWnd, out pid);
455
- string pName = "";
456
- try { pName = Process.GetProcessById((int)pid).ProcessName.ToLower(); } catch { }
497
+ uint pid;
498
+ GetWindowThreadProcessId(hWnd, out pid);
499
+ string pName = "";
500
+ try { pName = Process.GetProcessById((int)pid).ProcessName.ToLower(); } catch { }
457
501
 
458
- if (pName == target || pName.Contains(target) || t.StartsWith(target) || t.Contains(target))
459
- {
460
- foundHwnd = hWnd;
461
- return false;
462
- }
463
- }
464
- return true;
465
- }, IntPtr.Zero);
502
+ bool isBrowserMatch = (target == "browser" || target == "web browser" || target == "default browser" || target == "web" || target == "internet" ||
503
+ target.Contains("chrome") || target.Contains("edge") || target.Contains("brave")) &&
504
+ (pName.Contains("chrome") || pName.Contains("msedge") || pName.Contains("brave") || pName.Contains("firefox") ||
505
+ t.Contains("chrome") || t.Contains("edge") || t.Contains("brave") || t.Contains("firefox"));
506
+
507
+ bool isNotepadMatch = (target == "notepad" || target.Contains("notepad")) && (pName.Contains("notepad") || t.Contains("notepad"));
508
+
509
+ if (isBrowserMatch || isNotepadMatch || pName == target || pName.Contains(target) || t.StartsWith(target) || t.Contains(target))
510
+ {
511
+ foundHwnd = hWnd;
512
+ return false;
513
+ }
466
514
  }
515
+ return true;
516
+ }, IntPtr.Zero);
517
+
518
+ return foundHwnd;
519
+ }
467
520
 
521
+ public static bool FocusWindow(string titleOrApp)
522
+ {
523
+ try
524
+ {
525
+ IntPtr foundHwnd = FindWindowByApp(titleOrApp);
468
526
  if (foundHwnd != IntPtr.Zero)
469
527
  {
470
528
  if (IsIconic(foundHwnd))
@@ -473,29 +531,39 @@ namespace Scout.ComputerControl
473
531
  }
474
532
  else
475
533
  {
476
- ShowWindow(foundHwnd, SW_SHOW);
534
+ ShowWindow(foundHwnd, SW_SHOWNORMAL);
477
535
  }
478
536
 
479
- IntPtr fgHwnd = GetForegroundWindow();
480
- uint fgPid;
481
- uint fgThreadId = GetWindowThreadProcessId(fgHwnd, out fgPid);
482
- uint curThreadId = GetCurrentThreadId();
483
- if (fgThreadId != 0 && fgThreadId != curThreadId)
537
+ // Clean foreground transition using Win32 AttachThreadInput without injecting Alt keys
538
+ IntPtr foreHwnd = GetForegroundWindow();
539
+ uint forePid = 0;
540
+ uint foreThread = foreHwnd != IntPtr.Zero ? GetWindowThreadProcessId(foreHwnd, out forePid) : 0;
541
+ uint targetPid = 0;
542
+ uint targetThread = GetWindowThreadProcessId(foundHwnd, out targetPid);
543
+ uint currentThread = GetCurrentThreadId();
544
+
545
+ if (foreThread != 0 && foreThread != currentThread)
484
546
  {
485
- AttachThreadInput(curThreadId, fgThreadId, true);
547
+ AttachThreadInput(currentThread, foreThread, true);
548
+ }
549
+ if (targetThread != 0 && targetThread != currentThread && targetThread != foreThread)
550
+ {
551
+ AttachThreadInput(currentThread, targetThread, true);
486
552
  }
487
553
 
488
- keybd_event(0x12, 0, 0, UIntPtr.Zero);
489
- keybd_event(0x12, 0, 0x0002, UIntPtr.Zero);
490
- SetForegroundWindow(foundHwnd);
491
554
  BringWindowToTop(foundHwnd);
555
+ SetForegroundWindow(foundHwnd);
492
556
 
493
- if (fgThreadId != 0 && fgThreadId != curThreadId)
557
+ if (foreThread != 0 && foreThread != currentThread)
494
558
  {
495
- AttachThreadInput(curThreadId, fgThreadId, false);
559
+ AttachThreadInput(currentThread, foreThread, false);
560
+ }
561
+ if (targetThread != 0 && targetThread != currentThread && targetThread != foreThread)
562
+ {
563
+ AttachThreadInput(currentThread, targetThread, false);
496
564
  }
497
565
 
498
- Thread.Sleep(200);
566
+ Thread.Sleep(50);
499
567
  return true;
500
568
  }
501
569
  }
@@ -573,20 +641,30 @@ namespace Scout.ComputerControl
573
641
  {
574
642
  targetApp = "notepad.exe";
575
643
  }
576
- else if (lowerApp == "chrome" || lowerApp == "google chrome" || lowerApp == "google-chrome")
644
+ else if (lowerApp == "chrome" || lowerApp == "google chrome" || lowerApp == "google-chrome" ||
645
+ lowerApp == "browser" || lowerApp == "web browser" || lowerApp == "default browser" || lowerApp == "web" || lowerApp == "internet")
577
646
  {
578
647
  string localApp = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
579
- string[] chromeCandidates = new string[]
648
+ string[] browserCandidates = new string[]
580
649
  {
581
650
  @"C:\Program Files\Google\Chrome\Application\chrome.exe",
582
651
  @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
583
- Path.Combine(localApp, @"Google\Chrome\Application\chrome.exe")
652
+ Path.Combine(localApp, @"Google\Chrome\Application\chrome.exe"),
653
+ @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
654
+ @"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
655
+ @"C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
656
+ Path.Combine(localApp, @"BraveSoftware\Brave-Browser\Application\brave.exe")
584
657
  };
585
- foreach (string cPath in chromeCandidates)
658
+ foreach (string cPath in browserCandidates)
586
659
  {
587
660
  if (File.Exists(cPath)) { targetApp = cPath; break; }
588
661
  }
589
- if (targetApp.IndexOf("chrome", StringComparison.OrdinalIgnoreCase) < 0) targetApp = "chrome.exe";
662
+ if (targetApp.IndexOf("chrome", StringComparison.OrdinalIgnoreCase) < 0 &&
663
+ targetApp.IndexOf("edge", StringComparison.OrdinalIgnoreCase) < 0 &&
664
+ targetApp.IndexOf("brave", StringComparison.OrdinalIgnoreCase) < 0)
665
+ {
666
+ targetApp = "chrome.exe";
667
+ }
590
668
  }
591
669
  else if (lowerApp == "edge" || lowerApp == "msedge" || lowerApp == "microsoft edge")
592
670
  {
@@ -663,9 +741,50 @@ namespace Scout.ComputerControl
663
741
  }
664
742
  }
665
743
 
666
- // 1. Primary: Use Windows Shell (ShellExecuteEx via Process.Start with UseShellExecute = true).
667
- // This correctly activates modern Windows Store / UWP apps (like Windows 11 Notepad, Calculator, Terminal),
668
- // App Execution Aliases, and Win32 applications completely detached from this console process so they persist.
744
+ bool isBrowser = lowerApp == "chrome" || lowerApp == "google chrome" || lowerApp == "google-chrome" ||
745
+ lowerApp == "browser" || lowerApp == "web browser" || lowerApp == "default browser" || lowerApp == "web" || lowerApp == "internet" ||
746
+ lowerApp == "edge" || lowerApp == "msedge" || lowerApp == "microsoft edge" ||
747
+ lowerApp == "brave" || lowerApp == "brave browser" ||
748
+ targetApp.IndexOf("chrome.exe", StringComparison.OrdinalIgnoreCase) >= 0 ||
749
+ targetApp.IndexOf("msedge.exe", StringComparison.OrdinalIgnoreCase) >= 0 ||
750
+ targetApp.IndexOf("brave.exe", StringComparison.OrdinalIgnoreCase) >= 0;
751
+
752
+ if (isBrowser)
753
+ {
754
+ if (string.IsNullOrEmpty(targetArgs))
755
+ {
756
+ targetArgs = "--new-window https://www.google.com";
757
+ }
758
+ else if (!targetArgs.Contains("--new-window"))
759
+ {
760
+ targetArgs = "--new-window " + targetArgs;
761
+ }
762
+ }
763
+
764
+ // 1. Primary: Use Windows native ShellExecute directly from shell32.dll.
765
+ // In Windows, processes launched via ShellExecute are spawned directly as independent top-level desktop processes
766
+ // associated with the interactive user desktop session.
767
+ // They are 100% independent of this console process or caller job object,
768
+ // and remain open on the user's desktop indefinitely even after Scout CLI completes and exits.
769
+ try
770
+ {
771
+ IntPtr res = ShellExecute(IntPtr.Zero, "open", targetApp, string.IsNullOrEmpty(targetArgs) ? null : targetArgs, null, SW_SHOWNORMAL);
772
+ if ((long)res > 32)
773
+ {
774
+ Thread.Sleep(300);
775
+ IntPtr hw = FindWindowByApp(targetApp);
776
+ if (hw != IntPtr.Zero)
777
+ {
778
+ uint foundPid;
779
+ GetWindowThreadProcessId(hw, out foundPid);
780
+ pid = (int)foundPid;
781
+ }
782
+ return true;
783
+ }
784
+ }
785
+ catch { }
786
+
787
+ // 2. Secondary: Process.Start with UseShellExecute = true and Normal WindowStyle
669
788
  try
670
789
  {
671
790
  ProcessStartInfo psi = new ProcessStartInfo();
@@ -675,6 +794,7 @@ namespace Scout.ComputerControl
675
794
  psi.Arguments = targetArgs;
676
795
  }
677
796
  psi.UseShellExecute = true;
797
+ psi.WindowStyle = ProcessWindowStyle.Normal;
678
798
  Process p = Process.Start(psi);
679
799
  if (p != null)
680
800
  {
@@ -684,7 +804,7 @@ namespace Scout.ComputerControl
684
804
  }
685
805
  catch { }
686
806
 
687
- // 1b. If targetApp doesn't end with .exe, try targetApp + ".exe" via ShellExecute
807
+ // 2b. If targetApp doesn't end with .exe, try targetApp + ".exe" via ShellExecute
688
808
  if (!targetApp.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
689
809
  {
690
810
  try
@@ -696,6 +816,7 @@ namespace Scout.ComputerControl
696
816
  psi.Arguments = targetArgs;
697
817
  }
698
818
  psi.UseShellExecute = true;
819
+ psi.WindowStyle = ProcessWindowStyle.Normal;
699
820
  Process p = Process.Start(psi);
700
821
  if (p != null)
701
822
  {
@@ -706,7 +827,27 @@ namespace Scout.ComputerControl
706
827
  catch { }
707
828
  }
708
829
 
709
- // 2. Fallback: CreateProcess with DETACHED_PROCESS and CREATE_NEW_PROCESS_GROUP
830
+ // 3. Fallback: cmd.exe /c start "" <targetApp>
831
+ try
832
+ {
833
+ ProcessStartInfo psi = new ProcessStartInfo();
834
+ psi.FileName = "cmd.exe";
835
+ string startCmd = string.IsNullOrEmpty(targetArgs)
836
+ ? string.Format("/c start \"\" \"{0}\"", targetApp)
837
+ : string.Format("/c start \"\" \"{0}\" {1}", targetApp, targetArgs);
838
+ psi.Arguments = startCmd;
839
+ psi.CreateNoWindow = true;
840
+ psi.UseShellExecute = false;
841
+ Process p = Process.Start(psi);
842
+ if (p != null)
843
+ {
844
+ p.WaitForExit(1000);
845
+ return true;
846
+ }
847
+ }
848
+ catch { }
849
+
850
+ // 4. Fallback: CreateProcess with DETACHED_PROCESS, CREATE_NEW_PROCESS_GROUP, and CREATE_BREAKAWAY_FROM_JOB
710
851
  try
711
852
  {
712
853
  STARTUPINFO si = new STARTUPINFO();
@@ -727,7 +868,8 @@ namespace Scout.ComputerControl
727
868
 
728
869
  const uint DETACHED_PROCESS = 0x00000008;
729
870
  const uint CREATE_NEW_PROCESS_GROUP = 0x00000200;
730
- bool ok = CreateProcess(null, cmd, IntPtr.Zero, IntPtr.Zero, false, DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, IntPtr.Zero, null, ref si, out pi);
871
+ const uint CREATE_BREAKAWAY_FROM_JOB = 0x01000000;
872
+ bool ok = CreateProcess(null, cmd, IntPtr.Zero, IntPtr.Zero, false, DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB, IntPtr.Zero, null, ref si, out pi);
731
873
  if (ok)
732
874
  {
733
875
  pid = pi.dwProcessId;
@@ -826,9 +968,113 @@ namespace Scout.ComputerControl
826
968
  }
827
969
 
828
970
  public static bool TypeText(string text)
971
+ {
972
+ return TypeText(text, null);
973
+ }
974
+
975
+ public static bool TypeText(string text, string targetApp)
829
976
  {
830
977
  if (string.IsNullOrEmpty(text)) return true;
978
+
979
+ // Ensure window is active if targetApp is provided
980
+ if (!string.IsNullOrEmpty(targetApp))
981
+ {
982
+ FocusWindow(targetApp);
983
+ Thread.Sleep(80);
984
+ }
985
+
986
+ // Tier 1: Clipboard Paste (Ctrl+V) - 100% universal across Windows 10 & 11, XAML, Direct2D, Electron, and Win32
987
+ try
988
+ {
989
+ Clipboard.SetText(text);
990
+ Thread.Sleep(40);
991
+ keybd_event(0x11, 0, 0, UIntPtr.Zero); // VK_CONTROL down
992
+ keybd_event(0x56, 0, 0, UIntPtr.Zero); // 'V' down
993
+ Thread.Sleep(25);
994
+ keybd_event(0x56, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); // 'V' up
995
+ keybd_event(0x11, 0, KEYEVENTF_KEYUP, UIntPtr.Zero); // VK_CONTROL up
996
+ Thread.Sleep(50);
997
+ return true;
998
+ }
999
+ catch { }
1000
+
1001
+ // Tier 2: Try SendInput (Unicode)
831
1002
  if (TypeUnicode(text)) return true;
1003
+
1004
+ // Tier 3: Check if targetApp or foreground window has a classic Edit or RichEdit control
1005
+ try
1006
+ {
1007
+ IntPtr targetHwnd = IntPtr.Zero;
1008
+ if (!string.IsNullOrEmpty(targetApp))
1009
+ {
1010
+ targetHwnd = FindWindowByApp(targetApp);
1011
+ }
1012
+ if (targetHwnd == IntPtr.Zero)
1013
+ {
1014
+ targetHwnd = GetForegroundWindow();
1015
+ }
1016
+
1017
+ if (targetHwnd != IntPtr.Zero)
1018
+ {
1019
+ IntPtr editHwnd = IntPtr.Zero;
1020
+ StringBuilder sbClass = new StringBuilder(256);
1021
+ GetClassName(targetHwnd, sbClass, 256);
1022
+ string rootClass = sbClass.ToString();
1023
+ if (rootClass == "Edit" || rootClass.IndexOf("RichEdit", StringComparison.OrdinalIgnoreCase) >= 0)
1024
+ {
1025
+ editHwnd = targetHwnd;
1026
+ }
1027
+ else
1028
+ {
1029
+ EnumChildWindows(targetHwnd, (childHwnd, lParam) =>
1030
+ {
1031
+ StringBuilder childClass = new StringBuilder(256);
1032
+ GetClassName(childHwnd, childClass, 256);
1033
+ string cc = childClass.ToString();
1034
+ if (cc == "Edit" || cc.IndexOf("RichEdit", StringComparison.OrdinalIgnoreCase) >= 0)
1035
+ {
1036
+ editHwnd = childHwnd;
1037
+ return false;
1038
+ }
1039
+ return true;
1040
+ }, IntPtr.Zero);
1041
+ }
1042
+
1043
+ if (editHwnd != IntPtr.Zero)
1044
+ {
1045
+ SendMessage(editHwnd, EM_REPLACESEL, (IntPtr)1, text);
1046
+ ShowWindow(targetHwnd, SW_SHOWNORMAL);
1047
+ BringWindowToTop(targetHwnd);
1048
+ SetForegroundWindow(targetHwnd);
1049
+ return true;
1050
+ }
1051
+ }
1052
+ }
1053
+ catch { }
1054
+
1055
+ // Tier 4: Key-by-key injection via keybd_event Unicode
1056
+ try
1057
+ {
1058
+ foreach (char c in text)
1059
+ {
1060
+ if (c == '\r') continue;
1061
+ if (c == '\n')
1062
+ {
1063
+ keybd_event(0x0D, 0, 0, UIntPtr.Zero);
1064
+ keybd_event(0x0D, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
1065
+ }
1066
+ else
1067
+ {
1068
+ keybd_event(0, (byte)c, KEYEVENTF_UNICODE, UIntPtr.Zero);
1069
+ keybd_event(0, (byte)c, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, UIntPtr.Zero);
1070
+ }
1071
+ Thread.Sleep(5);
1072
+ }
1073
+ return true;
1074
+ }
1075
+ catch { }
1076
+
1077
+ // Tier 5: SendKeys fallback
832
1078
  try
833
1079
  {
834
1080
  SendKeys.SendWait(EscapeForSendKeys(text));
@@ -1231,7 +1477,8 @@ namespace Scout.ComputerControl
1231
1477
  if (act == "type")
1232
1478
  {
1233
1479
  string text = args.Length > 0 ? args[0] : "";
1234
- bool ok = TypeText(text);
1480
+ string target = args.Length > 1 ? args[1] : "";
1481
+ bool ok = TypeText(text, target);
1235
1482
  return string.Format("{{\"success\":{0},\"action\":\"type\",\"chars\":{1},\"activeWindow\":{2}}}",
1236
1483
  ok ? "true" : "false", text.Length, JsonEscape(GetActiveWindowTitle()));
1237
1484
  }
@@ -99,8 +99,16 @@ export const openai = new Proxy({}, {
99
99
  delete req.response_format;
100
100
  }
101
101
  const res = await client.chat.completions.create(req, options);
102
- if (res?.choices?.[0]?.message && !res.choices[0].message.content && res.choices[0].message.reasoning_content) {
103
- res.choices[0].message.content = res.choices[0].message.reasoning_content;
102
+ const choiceMsg = res?.choices?.[0]?.message;
103
+ if (choiceMsg) {
104
+ const rawReasoning = choiceMsg.reasoning_content || choiceMsg.thinking || choiceMsg.thought;
105
+ if (rawReasoning && typeof rawReasoning === 'string' && rawReasoning.trim().length > 0) {
106
+ choiceMsg.reasoning_content = rawReasoning.trim();
107
+ const c = (choiceMsg.content || '').trim();
108
+ if (!c || c.length < 15 || /^(?:i\s+will|let\s+me|i'll|starting|to\s+do\s+this|in\s+order\s+to)\b/i.test(c)) {
109
+ choiceMsg.content = rawReasoning.trim();
110
+ }
111
+ }
104
112
  }
105
113
  return res;
106
114
  }
@@ -253,6 +261,9 @@ export function sanitizeMessage(msg) {
253
261
  if (msg.function_call && typeof msg.function_call === 'object') {
254
262
  cleanMsg.function_call = msg.function_call;
255
263
  }
264
+ if (msg.reasoning_content !== undefined) {
265
+ cleanMsg.reasoning_content = msg.reasoning_content;
266
+ }
256
267
  return cleanMsg;
257
268
  }
258
269
  export function sanitizeMessages(messages) {
@@ -325,44 +336,53 @@ export function sanitizeMessages(messages) {
325
336
  const isOlder = i < keepIndexStart;
326
337
  if (typeof msg.content === 'string') {
327
338
  const isToolOutput = msg.content.includes('Tool Execution Result') || msg.role === 'tool' || Boolean(msg.tool_call_id);
328
- if (isOlder) {
329
- if (isToolOutput && msg.content.length > 250) {
339
+ const isFileCodeContent = msg.content.startsWith('File: ') || /^\d+\s*\|\s*/m.test(msg.content);
340
+ if (isFileCodeContent) {
341
+ // Code file contents: preserve up to 12,000 chars for recent, 5,000 chars for older turns
342
+ const codeLimit = isOlder ? 5000 : 12000;
343
+ if (msg.content.length > codeLimit) {
344
+ msg.content = msg.content.slice(0, codeLimit) + '\n...[File lines truncated for token efficiency]...';
345
+ }
346
+ }
347
+ else if (isOlder) {
348
+ // Terminal logs and general tool output
349
+ if (isToolOutput && msg.content.length > 500) {
330
350
  try {
331
351
  const origBytes = Buffer.byteLength(msg.content, 'utf-8');
332
352
  const cdp = compress(Buffer.from(msg.content, 'utf-8'), LEVEL_FAST);
333
353
  const ratio = (origBytes / Math.max(1, cdp.length)).toFixed(1);
334
- msg.content = msg.content.slice(0, 250) + `\n...[Codrop: older output compressed ${ratio}x for token efficiency]...`;
354
+ msg.content = msg.content.slice(0, 500) + `\n...[Codrop: older output compressed ${ratio}x for token efficiency]...`;
335
355
  }
336
356
  catch {
337
- msg.content = msg.content.slice(0, 250) + '\n...[Older tool output truncated for token efficiency]...';
357
+ msg.content = msg.content.slice(0, 500) + '\n...[Older tool output truncated for token efficiency]...';
338
358
  }
339
359
  }
340
- else if (msg.content.length > 400) {
341
- msg.content = msg.content.slice(0, 400) + '\n...[Older message truncated for token efficiency]...';
360
+ else if (msg.content.length > 800) {
361
+ msg.content = msg.content.slice(0, 800) + '\n...[Older message truncated for token efficiency]...';
342
362
  }
343
363
  }
344
364
  else {
345
- // For recent messages, cap individual output to 1000 chars max
346
- if (isToolOutput && msg.content.length > 1000) {
347
- msg.content = msg.content.slice(0, 1000) + '\n...[Recent tool output truncated for token efficiency]...';
365
+ // For recent non-code tool messages (e.g. build logs), cap individual output to 4,000 chars
366
+ if (isToolOutput && msg.content.length > 4000) {
367
+ msg.content = msg.content.slice(0, 4000) + '\n...[Recent tool output truncated for token efficiency]...';
348
368
  }
349
369
  }
350
370
  }
351
371
  // Prune older tool_calls arguments if large (e.g. large script payloads from previous turns)
352
372
  if (isOlder && Array.isArray(msg.tool_calls)) {
353
373
  for (const tc of msg.tool_calls) {
354
- if (tc?.function?.arguments && tc.function.arguments.length > 200) {
374
+ if (tc?.function?.arguments && tc.function.arguments.length > 300) {
355
375
  try {
356
376
  const parsed = JSON.parse(tc.function.arguments);
357
377
  for (const k of Object.keys(parsed)) {
358
- if (typeof parsed[k] === 'string' && parsed[k].length > 100) {
359
- parsed[k] = parsed[k].slice(0, 100) + '... [truncated]';
378
+ if (typeof parsed[k] === 'string' && parsed[k].length > 150) {
379
+ parsed[k] = parsed[k].slice(0, 150) + '... [truncated]';
360
380
  }
361
381
  }
362
382
  tc.function.arguments = JSON.stringify(parsed);
363
383
  }
364
384
  catch {
365
- tc.function.arguments = tc.function.arguments.slice(0, 200) + '...}';
385
+ // Keep intact if non-JSON to prevent syntax corruption
366
386
  }
367
387
  }
368
388
  }