Spaces:
Running
Running
File size: 7,632 Bytes
b9c7f0e | 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 | using System;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading;
using System.Threading.Tasks;
using FlowAPI.Application.Interfaces;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace FlowAPI.Application.Services
{
public class GeminiBridgeManager : IGeminiBridgeManager, IDisposable
{
private readonly ILogger<GeminiBridgeManager> _logger;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
private Process? _process;
private bool _isReady = false;
private readonly JsonSerializerOptions _serializeOptions;
public GeminiBridgeManager(ILogger<GeminiBridgeManager> logger, IHostApplicationLifetime appLifetime)
{
_logger = logger;
_serializeOptions = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
};
appLifetime.ApplicationStopping.Register(() =>
{
_logger.LogInformation("Application stopping, closing Gemini Bridge.");
Dispose();
});
}
private async Task EnsureProcessStartedAsync()
{
if (_process != null && !_process.HasExited && _isReady)
return;
_logger.LogInformation("Starting persistent Gemini Bridge process...");
string scriptPath = Path.Combine(AppContext.BaseDirectory, "gemini_bridge.py");
if (!File.Exists(scriptPath))
{
scriptPath = Path.Combine(Directory.GetCurrentDirectory(), "gemini_bridge.py");
}
if (!File.Exists(scriptPath))
{
scriptPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "gemini_bridge.py");
}
if (!File.Exists(scriptPath))
{
throw new FileNotFoundException("Could not locate gemini_bridge.py in application folders.");
}
var startInfo = new ProcessStartInfo
{
FileName = "python",
Arguments = $"\"{scriptPath}\" --headless",
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = Path.GetDirectoryName(scriptPath)
};
_process = new Process { StartInfo = startInfo };
_process.Start();
// Fire and forget error logging
_ = Task.Run(async () =>
{
while (_process != null && !_process.HasExited && !_process.StandardError.EndOfStream)
{
var errLine = await _process.StandardError.ReadLineAsync();
if (!string.IsNullOrEmpty(errLine))
{
_logger.LogWarning($"[GeminiBridge Python]: {errLine}");
}
}
});
// Wait for bridge to declare itself "ready"
var readyTimeout = Task.Delay(TimeSpan.FromSeconds(45));
var readReadyTask = Task.Run(async () =>
{
while (_process != null && !_process.HasExited && !_process.StandardOutput.EndOfStream)
{
var l = await _process.StandardOutput.ReadLineAsync();
if (l != null && l.Contains("\"type\": \"ready\""))
{
return true;
}
}
return false;
});
var completedTask = await Task.WhenAny(readReadyTask, readyTimeout);
if (completedTask == readyTimeout || !await readReadyTask)
{
try { _process.Kill(); } catch { }
_process = null;
throw new Exception("Timeout or failure waiting for persistent Gemini Browser Bridge to initialize.");
}
_isReady = true;
_logger.LogInformation("Persistent Gemini Bridge initialized successfully.");
}
public async Task<string> SendPromptAsync(string promptText, bool isNewChat, int timeoutSeconds = 120)
{
await _semaphore.WaitAsync();
try
{
await EnsureProcessStartedAsync();
if (_process == null || _process.HasExited)
throw new Exception("Gemini Bridge process is not running.");
var promptObj = new
{
type = "prompt",
id = Guid.NewGuid().ToString(),
new_chat = isNewChat,
content = promptText
};
string promptRequestJson = JsonSerializer.Serialize(promptObj, _serializeOptions);
// Send Prompt to standard input
await _process.StandardInput.WriteLineAsync(promptRequestJson);
await _process.StandardInput.FlushAsync();
// Await Gemini final response
var responseTimeout = Task.Delay(TimeSpan.FromSeconds(timeoutSeconds));
var readResponseTask = Task.Run(async () =>
{
while (_process != null && !_process.HasExited && !_process.StandardOutput.EndOfStream)
{
var l = await _process.StandardOutput.ReadLineAsync();
if (l != null && l.Contains("\"type\": \"response\"") && l.Contains($"\"id\": \"{promptObj.id}\""))
{
return l;
}
}
return null;
});
var responseCompletedTask = await Task.WhenAny(readResponseTask, responseTimeout);
if (responseCompletedTask == responseTimeout)
{
// If timeout occurs, we should probably kill the process to avoid desync
try { _process.Kill(); } catch { }
_process = null;
_isReady = false;
throw new Exception("Timeout waiting for AI response from Gemini Bridge.");
}
string? rawResponseJson = await readResponseTask;
if (string.IsNullOrEmpty(rawResponseJson))
{
throw new Exception("Did not receive a valid response block from the Gemini Bridge.");
}
return rawResponseJson;
}
finally
{
_semaphore.Release();
}
}
public void Dispose()
{
if (_process != null)
{
try
{
if (!_process.HasExited)
{
_process.StandardInput.WriteLine("{\"type\": \"exit\"}");
_process.StandardInput.Flush();
Thread.Sleep(500); // Give it a moment to exit gracefully
if (!_process.HasExited)
{
_process.Kill();
}
}
}
catch { }
_process.Dispose();
_process = null;
}
_semaphore.Dispose();
}
}
}
|