using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace XFEWorkflow.Plugins.AgentBrowser;
public sealed record AgentChatUser(string Id, string DisplayName, string AvatarDataUri = "");
public sealed record AgentChatRecord(string Type, string Id, string Text, string? MessageId = null,
string? Name = null, string? Input = null, string? ImagePath = null, string? UserId = null);
public sealed record AgentBrowserTab(string Id, string Url = "about:blank", string Title = "新标签页");
public sealed record AgentSessionSummary(string Id, string Title, DateTimeOffset UpdatedAt, int Messages)
{
public string UpdatedLabel => $"{UpdatedAt.LocalDateTime:MM-dd HH:mm} · {Messages} 条消息";
public override string ToString() => Title;
}
/// Public transcript and completed model turns. Context arrays are immutable snapshots: replace, never edit in place.
public sealed class AgentSession
{
public int SchemaVersion { get; set; } = 1;
public string Id { get; set; } = Guid.NewGuid().ToString("N");
public string Title { get; set; } = "新会话";
public bool TitleEdited { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
public string Draft { get; set; } = "";
public string BrowserUrl { get; set; } = "about:blank";
public List BrowserTabs { get; set; } = [];
public string ActiveBrowserTabId { get; set; } = "";
public bool UseLegacyBrowserProfile { get; set; }
public string ContextKey { get; set; } = "";
public JsonArray Context { get; set; } = [];
public bool TurnInProgress { get; set; }
public Dictionary Users { get; set; } = new(StringComparer.Ordinal);
public List Records { get; set; } = [];
public AgentSessionSummary Summary() => new(Id, Title, UpdatedAt, Records.Count(x => x.Type is "user" or "assistant_start"));
public AgentSession Snapshot() => new()
{
SchemaVersion = SchemaVersion, Id = Id, Title = Title, TitleEdited = TitleEdited, CreatedAt = CreatedAt,
UpdatedAt = UpdatedAt, Draft = Draft, BrowserUrl = BrowserUrl, ContextKey = ContextKey, Context = Context,
BrowserTabs = [.. BrowserTabs], ActiveBrowserTabId = ActiveBrowserTabId, UseLegacyBrowserProfile = UseLegacyBrowserProfile,
TurnInProgress = TurnInProgress, Users = new(Users, StringComparer.Ordinal), Records = [.. Records]
};
public void AddUser(string id, string text, AgentChatUser user)
{
if (!TitleEdited && !Records.Any(x => x.Type == "user"))
{
var words = string.Join(' ', text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
Title = string.Concat(words.EnumerateRunes().Take(32).Select(x => x.ToString())) + (words.EnumerateRunes().Skip(32).Any() ? "…" : "");
}
Users[user.Id] = user;
Records.Add(new("user", id, text, UserId: user.Id)); Touch();
}
public void Record(AgentEvent item, string? relativeImage = null)
{
if (item.Kind == "status" && item.Text != "已停止任务") return;
var index = Records.FindIndex(x => x.Id == item.Id && x.Type is not ("user" or "assistant_start"));
if (item.Kind is "assistant_delta" or "message_done")
{
if (item.Text.Length == 0 && index < 0) return;
var text = item.Kind == "assistant_delta" && index >= 0 ? Records[index].Text + item.Text : item.Text;
var record = new AgentChatRecord("message_done", item.Id, text, item.MessageId);
if (index >= 0) Records[index] = record; else Records.Add(record);
}
else if (item.Kind is "tool_start" or "tool_result" or "tool_error")
{
var previous = index >= 0 ? Records[index] : null;
var record = new AgentChatRecord(item.Kind, item.Id, item.Kind == "tool_start" ? "" : item.Text, item.MessageId,
item.Name, item.Kind == "tool_start" ? item.Text : previous?.Input, relativeImage ?? previous?.ImagePath);
if (index >= 0) Records[index] = record; else Records.Add(record);
}
else if (item.Kind is "assistant_start" or "error" or "status")
Records.Add(new(item.Kind, item.Id, item.Text, item.MessageId, item.Name));
else return;
Touch();
}
public void FinishPendingTools(string message)
{
for (var i = 0; i < Records.Count; i++)
if (Records[i].Type == "tool_start") Records[i] = Records[i] with { Type = "tool_error", Text = message };
}
public bool RecoverInterruptedTurn()
{
if (!TurnInProgress) return false;
TurnInProgress = false;
FinishPendingTools("上次运行被中断;未自动重新执行");
Records.Add(new("error", Guid.NewGuid().ToString("N"), "上次任务因应用退出而中断。已保留记录和此前完成的上下文,请确认当前网页后继续。"));
Touch(); return true;
}
public void Touch() => UpdatedAt = DateTimeOffset.UtcNow;
public void EnsureBrowserTabs()
{
BrowserTabs = (BrowserTabs ?? []).Where(x => x is not null && Guid.TryParseExact(x.Id, "N", out _)).DistinctBy(x => x.Id)
.Select(x => x with { Url = AllowedUrl(x.Url) ? x.Url : "about:blank", Title = string.IsNullOrWhiteSpace(x.Title) ? "新标签页" : x.Title }).ToList();
if (BrowserTabs.Count == 0) BrowserTabs.Add(new(Guid.NewGuid().ToString("N"), AllowedUrl(BrowserUrl) ? BrowserUrl : "about:blank"));
if (!BrowserTabs.Any(x => x.Id == ActiveBrowserTabId)) ActiveBrowserTabId = BrowserTabs[0].Id;
BrowserUrl = BrowserTabs.Single(x => x.Id == ActiveBrowserTabId).Url;
}
public static bool AllowedUrl(string? url) => url == "about:blank" || Uri.TryCreate(url, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https";
public static string Key(AgentOptions options) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new
{
endpoint = options.CompletionUri().AbsoluteUri, options.Model, skill = "bundled-browser-debugger", options.Thinking, options.Vision
}))));
public static string LegacyKey(AgentOptions options, string directory) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new
{
endpoint = options.CompletionUri().AbsoluteUri, options.Model, SkillDirectory = directory, options.Thinking, options.Vision
}))));
}
public sealed class AgentSessionCatalog
{
public int SchemaVersion { get; set; } = 1;
public string ActiveSessionId { get; set; } = "";
public List Sessions { get; set; } = [];
}