-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAIProcess.cs
More file actions
543 lines (486 loc) · 18.5 KB
/
AIProcess.cs
File metadata and controls
543 lines (486 loc) · 18.5 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
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using RalphController.Models;
namespace RalphController;
/// <summary>
/// Manages spawning and controlling AI CLI processes (Claude, Codex, etc.)
/// </summary>
public class AIProcess : IDisposable
{
private Process? _process;
private readonly RalphConfig _config;
private readonly AIProviderConfig _providerConfig;
private readonly StringBuilder _outputBuffer = new();
private readonly StringBuilder _errorBuffer = new();
private readonly StringBuilder _streamingTextBuffer = new();
private readonly StringBuilder _lineBuffer = new();
private readonly object _lock = new();
private string? _tempPromptFile;
private string? _tempScriptFile;
private bool _disposed;
/// <summary>Fired when stdout data is received</summary>
public event Action<string>? OnOutput;
/// <summary>Fired when stderr data is received</summary>
public event Action<string>? OnError;
/// <summary>Fired when the process exits</summary>
public event Action<int>? OnExit;
/// <summary>Whether the process is currently running</summary>
public bool IsRunning => _process is { HasExited: false };
/// <summary>Exit code of the last run (null if still running or never ran)</summary>
public int? ExitCode => _process?.HasExited == true ? _process.ExitCode : null;
/// <summary>The AI provider being used</summary>
public AIProvider Provider => _providerConfig.Provider;
/// <summary>All stdout captured from current/last run</summary>
public string Output
{
get { lock (_lock) return _outputBuffer.ToString(); }
}
/// <summary>All stderr captured from current/last run</summary>
public string Error
{
get { lock (_lock) return _errorBuffer.ToString(); }
}
public AIProcess(RalphConfig config, AIProviderConfig providerConfig)
{
_config = config;
_providerConfig = providerConfig;
}
public AIProcess(RalphConfig config) : this(config, config.ProviderConfig)
{
}
/// <summary>
/// Starts a new AI process with the given prompt piped to stdin
/// </summary>
/// <param name="prompt">The prompt to send</param>
/// <param name="cancellationToken">Cancellation token</param>
public async Task<bool> StartAsync(string prompt, CancellationToken cancellationToken = default)
{
if (IsRunning)
{
throw new InvalidOperationException("Process is already running");
}
// Clear buffers for new run
lock (_lock)
{
_outputBuffer.Clear();
_errorBuffer.Clear();
}
// Build arguments - some providers take prompt as argument, others via stdin
var arguments = _providerConfig.Arguments;
var useShell = false;
var useStdinRedirect = _providerConfig.UsesStdin;
string? scriptFile = null;
// On Windows, stdin-based commands need to use temp file + input redirection
// because .cmd files don't work well with direct stdin piping
if (OperatingSystem.IsWindows() && _providerConfig.UsesStdin)
{
var tempFile = Path.GetTempFileName();
await File.WriteAllTextAsync(tempFile, prompt, cancellationToken);
_tempPromptFile = tempFile;
// Use shell with input redirection from temp file
var fullCmd = $"{_providerConfig.ExecutablePath} {arguments} < \"{tempFile}\"";
arguments = $"/c {fullCmd}";
useShell = true;
useStdinRedirect = false; // We're using file redirection instead
}
else if (_providerConfig.UsesPromptArgument)
{
// Write prompt to temp file and create a shell script to execute
var tempFile = Path.GetTempFileName();
await File.WriteAllTextAsync(tempFile, prompt, cancellationToken);
_tempPromptFile = tempFile;
// Create a temp script file to avoid quoting issues
// Close stdin to prevent tools like opencode from hanging waiting for input
if (OperatingSystem.IsWindows())
{
scriptFile = Path.GetTempFileName() + ".bat";
// Windows batch file - read prompt from temp file and pass to command
var scriptContent = $"@echo off\ntype \"{tempFile}\" | {_providerConfig.ExecutablePath} {arguments}";
await File.WriteAllTextAsync(scriptFile, scriptContent, cancellationToken);
}
else
{
scriptFile = Path.GetTempFileName() + ".sh";
var scriptContent = $"#!/bin/bash\nexec < /dev/null\n{_providerConfig.ExecutablePath} {arguments} \"$(cat '{tempFile}')\"";
await File.WriteAllTextAsync(scriptFile, scriptContent, cancellationToken);
}
_tempScriptFile = scriptFile;
arguments = OperatingSystem.IsWindows() ? $"/c \"{scriptFile}\"" : scriptFile;
useShell = true;
}
else if (!_providerConfig.UsesStdin)
{
// Write prompt to temp file and use shell input redirection
var tempFile = Path.GetTempFileName();
await File.WriteAllTextAsync(tempFile, prompt, cancellationToken);
_tempPromptFile = tempFile;
// Use shell with input redirection from temp file
if (OperatingSystem.IsWindows())
{
var fullCmd = $"{_providerConfig.ExecutablePath} {arguments} < \"{tempFile}\"";
arguments = $"/c {fullCmd}";
}
else
{
var fullCmd = $"{_providerConfig.ExecutablePath} {arguments} < '{tempFile}'";
arguments = $"-c \"{fullCmd}\"";
}
useShell = true;
}
var psi = new ProcessStartInfo
{
FileName = useShell
? (OperatingSystem.IsWindows() ? "cmd.exe" : "/bin/bash")
: _providerConfig.ExecutablePath,
Arguments = arguments,
WorkingDirectory = _config.TargetDirectory,
RedirectStandardInput = useStdinRedirect,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
if (_providerConfig.Provider == AIProvider.OpenCode)
{
psi.Environment["OPENCODE_DISABLE_AUTOUPDATE"] = "true";
psi.Environment["OPENCODE_PERMISSION"] = "{\"permission\":\"allow\"}";
}
try
{
_process = new Process { StartInfo = psi };
_process.OutputDataReceived += (_, e) =>
{
if (e.Data is not null)
{
if (_providerConfig.UsesStreamJson)
{
// Parse stream-json format to extract text content
var text = ParseStreamJsonLine(e.Data);
if (text != null)
{
lock (_lock)
{
_streamingTextBuffer.Append(text);
_outputBuffer.Append(text);
_lineBuffer.Append(text);
// Emit complete lines as they become available
var content = _lineBuffer.ToString();
var lastNewline = content.LastIndexOf('\n');
if (lastNewline >= 0)
{
// Extract and emit complete lines
var completeLines = content.Substring(0, lastNewline + 1);
_lineBuffer.Clear();
_lineBuffer.Append(content.Substring(lastNewline + 1));
// Emit each complete line
foreach (var line in completeLines.Split('\n', StringSplitOptions.None))
{
if (!string.IsNullOrEmpty(line))
OnOutput?.Invoke(line);
}
}
}
}
}
else if (_providerConfig.Provider == AIProvider.OpenCode)
{
// Parse OpenCode JSON format
var text = ParseOpenCodeJsonLine(e.Data);
if (text != null)
{
lock (_lock)
{
_outputBuffer.Append(text);
OnOutput?.Invoke(text);
}
}
}
else
{
lock (_lock) _outputBuffer.AppendLine(e.Data);
OnOutput?.Invoke(e.Data);
}
}
};
_process.ErrorDataReceived += (_, e) =>
{
if (e.Data is not null)
{
lock (_lock) _errorBuffer.AppendLine(e.Data);
OnError?.Invoke(e.Data);
}
};
_process.EnableRaisingEvents = true;
_process.Exited += (_, _) =>
{
// Flush any remaining buffered text
if (_providerConfig.UsesStreamJson)
{
lock (_lock)
{
if (_lineBuffer.Length > 0)
{
OnOutput?.Invoke(_lineBuffer.ToString());
_lineBuffer.Clear();
}
}
}
OnExit?.Invoke(_process.ExitCode);
};
_process.Start();
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
// Write prompt to stdin and close it (if using stdin redirect)
if (useStdinRedirect)
{
await _process.StandardInput.WriteAsync(prompt);
_process.StandardInput.Close();
}
return true;
}
catch (Exception ex)
{
var providerName = _providerConfig.Provider.ToString();
lock (_lock) _errorBuffer.AppendLine($"Failed to start {providerName}: {ex.Message}");
OnError?.Invoke($"Failed to start {providerName}: {ex.Message}");
return false;
}
}
private static string EscapeArgument(string arg)
{
return arg.Replace("\\", "\\\\").Replace("\"", "\\\"");
}
/// <summary>
/// Parse a line of stream-json output to extract text content
/// </summary>
private static string? ParseStreamJsonLine(string line)
{
try
{
// Skip empty lines or non-JSON
if (string.IsNullOrWhiteSpace(line) || !line.StartsWith("{"))
return null;
using var doc = JsonDocument.Parse(line);
var root = doc.RootElement;
// Check for content_block_delta with text_delta
if (root.TryGetProperty("type", out var typeEl) && typeEl.GetString() == "stream_event")
{
if (root.TryGetProperty("event", out var eventEl))
{
if (eventEl.TryGetProperty("type", out var eventTypeEl) &&
eventTypeEl.GetString() == "content_block_delta")
{
if (eventEl.TryGetProperty("delta", out var deltaEl) &&
deltaEl.TryGetProperty("text", out var textEl))
{
return textEl.GetString();
}
}
}
}
return null;
}
catch
{
return null;
}
}
/// <summary>
/// Parse a line of OpenCode JSON output to extract text content
/// </summary>
private static string? ParseOpenCodeJsonLine(string line)
{
try
{
if (string.IsNullOrWhiteSpace(line) || !line.StartsWith("{"))
return null;
using var doc = JsonDocument.Parse(line);
var root = doc.RootElement;
if (root.TryGetProperty("type", out var typeEl))
{
var type = typeEl.GetString();
if (type == "text" || type == "text_delta" || type == "content_block_delta")
{
// Check if text is directly on root
if (root.TryGetProperty("text", out var textEl))
{
return textEl.GetString();
}
// Check in part.text
if (root.TryGetProperty("part", out var partEl) && partEl.TryGetProperty("text", out textEl))
{
return textEl.GetString();
}
// Other formats
if (root.TryGetProperty("content", out textEl))
{
return textEl.GetString();
}
if (root.TryGetProperty("delta", out var deltaEl))
{
if (deltaEl.TryGetProperty("text", out textEl))
{
return textEl.GetString();
}
}
}
else if (type == "error")
{
string? errorMsg = null;
if (root.TryGetProperty("error", out var errorEl))
{
if (errorEl.TryGetProperty("message", out var msgEl))
{
errorMsg = msgEl.GetString();
}
else if (errorEl.TryGetProperty("data", out var dataEl) &&
dataEl.TryGetProperty("message", out var dataMsgEl))
{
errorMsg = dataMsgEl.GetString();
}
}
else if (root.TryGetProperty("part", out var partEl) && partEl.TryGetProperty("error", out errorEl))
{
if (errorEl.TryGetProperty("message", out var msgEl))
{
errorMsg = msgEl.GetString();
}
}
if (errorMsg != null)
{
return $"Error: {errorMsg}";
}
}
}
return null;
}
catch
{
return null;
}
}
/// <summary>
/// Waits for the process to exit
/// </summary>
public async Task<int> WaitForExitAsync(CancellationToken cancellationToken = default)
{
if (_process is null)
{
throw new InvalidOperationException("Process has not been started");
}
await _process.WaitForExitAsync(cancellationToken);
return _process.ExitCode;
}
/// <summary>
/// Runs a complete iteration - start, wait for exit, return result
/// </summary>
public async Task<AIResult> RunAsync(string prompt, CancellationToken cancellationToken = default)
{
var started = await StartAsync(prompt, cancellationToken);
if (!started)
{
return new AIResult
{
Success = false,
ExitCode = -1,
Output = Output,
Error = Error
};
}
var exitCode = await WaitForExitAsync(cancellationToken);
return new AIResult
{
Success = exitCode == 0,
ExitCode = exitCode,
Output = Output,
Error = Error
};
}
/// <summary>
/// Attempts to gracefully stop the process, then forcefully if needed
/// </summary>
public async Task StopAsync(TimeSpan? gracePeriod = null)
{
if (_process is null || _process.HasExited)
{
return;
}
gracePeriod ??= TimeSpan.FromSeconds(5);
try
{
// Try graceful termination first (SIGINT on Unix, Ctrl+C on Windows)
if (OperatingSystem.IsWindows())
{
// On Windows, we can't easily send Ctrl+C, so we just kill
_process.Kill(entireProcessTree: true);
}
else
{
// On Unix, send SIGINT first
Process.Start("kill", $"-INT {_process.Id}");
// Wait for grace period
var exited = await WaitForExitWithTimeoutAsync(gracePeriod.Value);
if (!exited)
{
// Force kill
_process.Kill(entireProcessTree: true);
}
}
}
catch (InvalidOperationException)
{
// Process already exited
}
}
private async Task<bool> WaitForExitWithTimeoutAsync(TimeSpan timeout)
{
using var cts = new CancellationTokenSource(timeout);
try
{
await _process!.WaitForExitAsync(cts.Token);
return true;
}
catch (OperationCanceledException)
{
return false;
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
if (_process is not null)
{
if (!_process.HasExited)
{
try { _process.Kill(entireProcessTree: true); }
catch { /* ignore */ }
}
_process.Dispose();
}
// Clean up temp prompt file if used
if (_tempPromptFile is not null && File.Exists(_tempPromptFile))
{
try { File.Delete(_tempPromptFile); }
catch { /* ignore */ }
}
// Clean up temp script file if used
if (_tempScriptFile is not null && File.Exists(_tempScriptFile))
{
try { File.Delete(_tempScriptFile); }
catch { /* ignore */ }
}
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Result of an AI process execution
/// </summary>
public record AIResult
{
public required bool Success { get; init; }
public required int ExitCode { get; init; }
public required string Output { get; init; }
public required string Error { get; init; }
}