using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Plugins.AgentBrowser;
/// <summary>One Node process per turn, persistent across that turn's tool calls. Stopping it never kills the embedded browser.</summary>
public sealed class SkillBrowserRuntime(AgentOptions options, string bridgeFile, string endpoint, string targetId, string workDirectory,
Func<JsonObject, CancellationToken, Task<JsonObject>>? tabs = null) : IAgentBrowserRuntime
{
private Process? process;
private Task<string>? stderr;
private BrowserSkill? loadedSkill;
private long sequence;
private string selectedTargetId = targetId;
private readonly SemaphoreSlim gate = new(1);
public async Task<JsonObject> 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("插件的内置浏览器运行时无法启动,请重新安装插件");
stderr = DrainErrorAsync(process.StandardError);
return await RequestAsync(new() { ["op"] = "start", ["skill"] = skill.Directory, ["endpoint"] = endpoint, ["targetId"] = selectedTargetId, ["workDir"] = workDirectory }, ct);
}
public async Task<AgentToolResult> 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));
JsonObject? tabState = null;
if (tabs is not null)
{
tabState = await tabs(tool == "browser_tabs" ? arguments : new() { ["operation"] = "list" }, ct);
var current = tabState.String("targetId");
if (current != selectedTargetId)
{
await RequestAsync(new() { ["op"] = "select_target", ["targetId"] = current }, ct);
selectedTargetId = current;
}
}
if (tool == "browser_tabs") return new(tabState?.Display() ?? throw new NotSupportedException("当前宿主不支持标签页管理"));
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((tool == "browser_observe" && tabState is not null ? "当前会话的浏览器标签:\n" + tabState.Display() + "\n当前页面:\n" : "") + result.String("text"), image);
}
private async Task<JsonObject> 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<long>() != request["id"]!.GetValue<long>()) 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<string> 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(); }
}
}
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Plugins.AgentBrowser;
/// <summary>One Node process per turn, persistent across that turn's tool calls. Stopping it never kills the embedded browser.</summary>
public sealed class SkillBrowserRuntime(AgentOptions options, string bridgeFile, string endpoint, string targetId, string workDirectory,
Func<JsonObject, CancellationToken, Task<JsonObject>>? tabs = null) : IAgentBrowserRuntime
{
private Process? process;
private Task<string>? stderr;
private BrowserSkill? loadedSkill;
private long sequence;
private string selectedTargetId = targetId;
private readonly SemaphoreSlim gate = new(1);
public async Task<JsonObject> 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("插件的内置浏览器运行时无法启动,请重新安装插件");
stderr = DrainErrorAsync(process.StandardError);
return await RequestAsync(new() { ["op"] = "start", ["skill"] = skill.Directory, ["endpoint"] = endpoint, ["targetId"] = selectedTargetId, ["workDir"] = workDirectory }, ct);
}
public async Task<AgentToolResult> 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));
JsonObject? tabState = null;
if (tabs is not null)
{
tabState = await tabs(tool == "browser_tabs" ? arguments : new() { ["operation"] = "list" }, ct);
var current = tabState.String("targetId");
if (current != selectedTargetId)
{
await RequestAsync(new() { ["op"] = "select_target", ["targetId"] = current }, ct);
selectedTargetId = current;
}
}
if (tool == "browser_tabs") return new(tabState?.Display() ?? throw new NotSupportedException("当前宿主不支持标签页管理"));
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((tool == "browser_observe" && tabState is not null ? "当前会话的浏览器标签:\n" + tabState.Display() + "\n当前页面:\n" : "") + result.String("text"), image);
}
private async Task<JsonObject> 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<long>() != request["id"]!.GetValue<long>()) 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<string> 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(); }
}
}