-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
327 lines (272 loc) · 11.2 KB
/
Copy pathProgram.cs
File metadata and controls
327 lines (272 loc) · 11.2 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
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
class Program
{
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
private static bool isInjecting = false;
private static bool isInApolloMode = false;
private static StringBuilder rollingBuffer = new StringBuilder();
private static StringBuilder commandBuffer = new StringBuilder();
private static int apolloCharCount = 0;
// Added '?' to explicitly allow these to be null before they initialize
private static Process? _pythonProcess;
private static StreamWriter? _pythonIn;
private static StreamReader? _pythonOut;
[STAThread]
static void Main()
{
Console.WriteLine("Apollo System Booting...");
StartPythonEngine();
_hookID = SetHook(_proc);
Application.Run();
UnhookWindowsHookEx(_hookID);
if (_pythonProcess != null && !_pythonProcess.HasExited)
{
_pythonProcess.Kill();
}
}
private static void StartPythonEngine()
{
// 1. Check the .exe folder first (for when you publish it later)
string exeDir = AppDomain.CurrentDomain.BaseDirectory;
string scriptPath = Path.Combine(exeDir, "apollo_chat.py");
// 2. If it's not there, check the current working directory (for 'dotnet run' in development)
if (!File.Exists(scriptPath))
{
scriptPath = Path.Combine(Environment.CurrentDirectory, "apollo_chat.py");
}
// 3. If it's STILL not there, pause and tell the user!
if (!File.Exists(scriptPath))
{
Console.WriteLine($"\n[ERROR] Could not find 'apollo_chat.py'!");
Console.WriteLine($"Make sure it is saved in: {Environment.CurrentDirectory}");
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine(); // Pauses the console so it doesn't instantly vanish
Environment.Exit(1);
}
var startInfo = new ProcessStartInfo
{
FileName = "python",
Arguments = $"\"{scriptPath}\"",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8,
StandardInputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8
};
Console.WriteLine("Starting Python AI Engine... (Launching browser)");
try
{
_pythonProcess = Process.Start(startInfo) ?? throw new InvalidOperationException("Failed to start Python.");
}
catch (Exception ex)
{
Console.WriteLine($"\n[ERROR] Failed to launch Python. Is Python installed and added to your PATH?");
Console.WriteLine($"Details: {ex.Message}");
Console.WriteLine("\nPress ENTER to exit...");
Console.ReadLine();
Environment.Exit(1);
}
_pythonIn = _pythonProcess.StandardInput;
_pythonOut = _pythonProcess.StandardOutput;
// Forward Python stderr to console so we see any script errors
var stderrReader = _pythonProcess.StandardError;
Thread stderrThread = new Thread(() =>
{
string? line;
while ((line = stderrReader.ReadLine()) != null)
Console.WriteLine("[Python] {0}", line);
});
stderrThread.IsBackground = true;
stderrThread.Start();
while (true)
{
string? line = _pythonOut.ReadLine();
if (line == "READY") break;
// If the python script crashes (like a syntax error), print it out so we know
if (line != null && line.Contains("Error", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine($"[PYTHON ERROR] {line}");
}
}
Console.WriteLine("Apollo Engine is READY. Listening for @apo ...");
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using Process curProcess = Process.GetCurrentProcess();
using ProcessModule curModule = curProcess.MainModule!;
return SetWindowsHookEx(13, proc, GetModuleHandle(curModule.ModuleName), 0);
}
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
private const int WM_KEYDOWN = 0x0100;
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN && !isInjecting)
{
int vkCode = Marshal.ReadInt32(lParam);
Keys key = (Keys)vkCode;
char? typedChar = KeyToChar(key);
if (typedChar != null)
{
rollingBuffer.Append(typedChar);
if (rollingBuffer.Length > 30)
rollingBuffer.Remove(0, rollingBuffer.Length - 30);
if (!isInApolloMode && rollingBuffer.ToString().EndsWith("@apo"))
{
isInApolloMode = true;
commandBuffer.Clear();
apolloCharCount = 4;
}
else if (isInApolloMode)
{
commandBuffer.Append(typedChar);
apolloCharCount++;
if (commandBuffer.ToString().EndsWith("@@"))
{
isInApolloMode = false;
apolloCharCount = 0;
commandBuffer.Clear();
rollingBuffer.Clear();
TriggerApollo();
}
}
}
if (key == Keys.Back)
{
if (rollingBuffer.Length > 0)
rollingBuffer.Remove(rollingBuffer.Length - 1, 1);
if (isInApolloMode && apolloCharCount > 0)
{
apolloCharCount--;
if (commandBuffer.Length > 0)
commandBuffer.Remove(commandBuffer.Length - 1, 1);
if (apolloCharCount < 4)
isInApolloMode = false;
}
}
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
private static char? KeyToChar(Keys key)
{
if (key >= Keys.A && key <= Keys.Z) return key.ToString().ToLower()[0];
if (key == Keys.Space) return ' ';
if (key == Keys.D2 && (Control.ModifierKeys & Keys.Shift) != 0) return '@';
return null;
}
private static string? GetChatResponse(string promptText)
{
try
{
_pythonIn!.WriteLine(promptText);
_pythonIn!.Flush();
// Python sends: base64-encoded response line, then "@@END_OF_RESPONSE@@"
string? line = _pythonOut!.ReadLine();
if (line == null)
return "[Error: No response from Python.]";
if (line == "@@END_OF_RESPONSE@@")
return string.Empty;
// Decode base64 payload (response may be multi-line; Python encodes the whole string)
string result;
try
{
byte[] bytes = Convert.FromBase64String(line);
result = Encoding.UTF8.GetString(bytes);
}
catch
{
return "[Error: Invalid response encoding.]";
}
_pythonOut.ReadLine(); // consume delimiter
return result;
}
catch (Exception ex)
{
Console.WriteLine("Stream error: " + ex.Message);
return "[Error: Communication with Python lost.]";
}
}
private static void TriggerApollo()
{
isInjecting = true;
Thread macroThread = new Thread(() =>
{
try
{
// Select from the current cursor position (after @@) backwards up to @apo,
// possibly spanning multiple lines. We grow the selection upwards until we
// see "@apo" in the clipboard or we hit a reasonable line limit.
const int maxSelectionLines = 40;
SendKeys.SendWait("+{HOME}");
Thread.Sleep(50);
SendKeys.SendWait("^c");
Thread.Sleep(100);
string clipboardText = Clipboard.GetText();
int guard = 0;
while (!clipboardText.Contains("@apo") && guard < maxSelectionLines)
{
guard++;
SendKeys.SendWait("+{UP}");
Thread.Sleep(50);
SendKeys.SendWait("^c");
Thread.Sleep(100);
clipboardText = Clipboard.GetText();
}
string extractedPrompt = "";
string restOfLine = clipboardText;
// Use the last occurrence of "@apo" so we bind to the innermost Apollo block
int start = clipboardText.LastIndexOf("@apo");
int end = clipboardText.LastIndexOf("@@");
if (start >= 0 && end > start)
{
extractedPrompt = clipboardText.Substring(start + 4, end - start - 4).Trim();
restOfLine = clipboardText.Remove(start, end - start + 2);
}
SendKeys.SendWait("{DELETE}");
Thread.Sleep(50);
const string placeholder = " processing... ";
Clipboard.SetText(restOfLine + placeholder);
SendKeys.SendWait("^v");
Thread.Sleep(100);
string? chatResponse = GetChatResponse(extractedPrompt);
if (!string.IsNullOrEmpty(chatResponse))
{
for (int i = 0; i < placeholder.Length; i++) SendKeys.SendWait("{LEFT}");
for (int i = 0; i < placeholder.Length; i++) SendKeys.SendWait("+{RIGHT}");
Clipboard.SetText(" " + chatResponse + " ");
SendKeys.SendWait("^v");
}
}
catch (Exception ex)
{
Console.WriteLine("Macro error: " + ex.Message);
}
finally
{
isInjecting = false;
}
});
macroThread.SetApartmentState(ApartmentState.STA);
macroThread.Start();
}
#region WinAPI
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr GetModuleHandle(string? lpModuleName);
#endregion
}