using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Plugins.AgentBrowser;
/// One Node process per turn, persistent across that turn's tool calls. Stopping it never kills the embedded browser.
public sealed class SkillBrowserRuntime(AgentOptions options, string bridgeFile, string endpoint, string targetId, string workDirectory) : IAgentBrowserRuntime
{
private Process? process;
private Task? stderr;
private BrowserSkill? loadedSkill;
private long sequence;
private readonly SemaphoreSlim gate = new(1);
public async Task StartAsync(BrowserSkill skill, CancellationToken ct)
{
if (process is not null) throw new InvalidOperationException("技能会话已启动");
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || !uri.IsLoopback || uri.Scheme != "http") throw new ArgumentException("技能只允许连接本应用的回环 CDP 地址");
Directory.CreateDirectory(workDirectory);
loadedSkill = skill;
var start = new ProcessStartInfo(options.NodeExecutable)
{
UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true,
StandardInputEncoding = new UTF8Encoding(false), StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8,
WorkingDirectory = workDirectory
};
start.ArgumentList.Add(bridgeFile);
process = Process.Start(start) ?? throw new IOException("无法启动 Node.js 22+,请检查 Agent 设置中的 Node.js 路径");
stderr = DrainErrorAsync(process.StandardError);
return await RequestAsync(new() { ["op"] = "start", ["skill"] = skill.Directory, ["endpoint"] = endpoint, ["targetId"] = targetId, ["workDir"] = workDirectory }, ct);
}
public async Task ExecuteAsync(string tool, JsonObject arguments, CancellationToken ct)
{
if (loadedSkill is null) throw new InvalidOperationException("技能尚未导入");
if (tool == "read_skill") return new(await loadedSkill.ReadReferenceAsync(arguments.String("path"), ct));
if (tool is not ("browser_observe" or "browser_execute" or "browser_screenshot")) throw new NotSupportedException("未知工具:" + tool);
var result = await RequestAsync(new() { ["op"] = tool, ["arguments"] = arguments.DeepClone() }, ct);
string? image = null;
if (result.String("imagePath") is { Length: > 0 } file)
{
var root = Path.GetFullPath(workDirectory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
file = Path.GetFullPath(file);
if (!file.StartsWith(root, StringComparison.OrdinalIgnoreCase) || !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || new FileInfo(file).Length > 8 * 1024 * 1024)
throw new IOException("技能返回的截图路径或大小无效");
image = file;
}
return new(result.String("text"), image);
}
private async Task RequestAsync(JsonObject request, CancellationToken ct)
{
await gate.WaitAsync(ct);
try
{
var child = process ?? throw new ObjectDisposedException(nameof(SkillBrowserRuntime));
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(75));
using var registration = timeout.Token.Register(() => Kill(child));
request["id"] = Interlocked.Increment(ref sequence);
await child.StandardInput.WriteLineAsync(request.ToJsonString().AsMemory(), timeout.Token);
await child.StandardInput.FlushAsync(timeout.Token);
// Read in chunks: a hostile/buggy script cannot allocate an unbounded line in the UI process.
var line = new StringBuilder(); var buffer = new char[4096];
while (true)
{
var read = await child.StandardOutput.ReadAsync(buffer, timeout.Token);
if (read == 0) throw new IOException("技能进程已退出:" + (stderr is null ? "" : await stderr));
line.Append(buffer, 0, read);
if (line.Length > 2 * 1024 * 1024) { Kill(child); throw new IOException("技能响应超过 2 MiB"); }
if (line[^1] == '\n') break;
}
var response = JsonNode.Parse(line.ToString())!.AsObject();
if (response["id"]?.GetValue() != request["id"]!.GetValue()) throw new IOException("技能响应序号不匹配");
if (!response.Boolean("ok")) throw new InvalidOperationException(response.String("error", "技能执行失败"));
return response["result"]?.AsObject() ?? new();
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested) { throw new TimeoutException("browser-debugger 操作超过 75 秒,已停止技能进程"); }
finally { gate.Release(); }
}
private static async Task DrainErrorAsync(StreamReader reader)
{
var text = new StringBuilder(); var buffer = new char[2048]; int count;
while ((count = await reader.ReadAsync(buffer)) > 0) { if (text.Length < 16384) text.Append(buffer, 0, Math.Min(count, 16384 - text.Length)); }
return text.ToString();
}
private static void Kill(Process child) { try { if (!child.HasExited) child.Kill(entireProcessTree: true); } catch (InvalidOperationException) { } catch (System.ComponentModel.Win32Exception) { } }
public async ValueTask DisposeAsync()
{
if (process is not { } child) return;
try
{
if (!child.HasExited)
{
using var close = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try { await RequestAsync(new() { ["op"] = "close" }, close.Token); } catch { Kill(child); }
}
using var exit = new CancellationTokenSource(TimeSpan.FromSeconds(3));
try { await child.WaitForExitAsync(exit.Token); } catch (OperationCanceledException) { Kill(child); }
}
finally { process = null; child.Dispose(); gate.Dispose(); }
}
}