199 lines
15 KiB
C#

using System.Security.Cryptography;
using System.Text;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Agent;
public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai = null,DocumentWorkspaceWork? workspace = null)
{
private readonly object gate = new();
private readonly Dictionary<Guid, WordInstance> instances = [];
private const int MaxSnapshotCharacters = 16 * 1024 * 1024;
private const int MaxTotalCharacters = 64 * 1024 * 1024;
private int totalCharacters;
private int totalFragments;
private int totalBoundaries;
private int totalSuggestions;
public int SessionCount { get { lock (gate) return instances.Values.Sum(i => i.Documents.Count); } }
public void Attach(Guid instance, Guid lease)
{
lock (gate)
{
if (instance == Guid.Empty || (!instances.ContainsKey(instance) && instances.Count >= 8)) throw new InvalidDataException("Word instance capacity/identity invalid.");
DetachCore(instance);
instances[instance] = new WordInstance(lease);
}
}
public void Detach(Guid instance, Guid lease) { lock (gate) { if (instances.TryGetValue(instance, out var state) && state.Lease == lease) DetachCore(instance); } }
private void DetachCore(Guid instance)
{
if (instances.Remove(instance, out var old)) foreach(var document in old.Documents.Values) ClearDocument(document);
}
private void ClearPending(DocumentState document)
{
totalCharacters -= document.Pending?.Characters ?? 0;
totalFragments -= document.Pending?.Fragments.Count ?? 0;
document.Pending = null;
}
private void ClearDocument(DocumentState document)
{
ai?.Clear(document.Descriptor.SessionId);workspace?.Clear(document.Descriptor.SessionId);
totalSuggestions -= document.Analysis?.Count ?? 0;document.Analysis=null;
ClearPending(document);totalBoundaries -= document.Boundaries.Count;document.Boundaries=[];
}
public Message Apply(Guid lease, Message message)
{
lock (gate)
{
var answer = new Message { Kind = "response", CorrelationId = message.CorrelationId, WordInstanceId = message.WordInstanceId, SessionId = message.SessionId, Revision = message.Revision, SnapshotId=message.SnapshotId, Status = "ok" };
if (!instances.TryGetValue(message.WordInstanceId, out var word) || word.Lease != lease) return Reject(answer,"wrong-instance");
if (message.Sequence <= word.LastSequence) return Reject(answer,"stale-sequence");
word.LastSequence = message.Sequence;
if (message.Kind == "ping") return answer;
if(message.Kind is "cloud-status" or "cloud-check" or "cloud-connect" or "cloud-signout")
{
answer.Kind="cloud-status";if(cloud==null)return Reject(answer,"cloud-unavailable");
try{if(message.Kind=="cloud-check")_=cloud.CheckConnection();if(message.Kind=="cloud-connect"){ai?.Dispose();workspace?.ClearAll();cloud.Connect(message.ServerUrl);}if(message.Kind=="cloud-signout"){ai?.Dispose();workspace?.ClearAll();cloud.SignOut();}}
catch(ArgumentException){return Reject(answer,"invalid-server-url");}
var status=cloud.Status();answer.Kind="cloud-status";answer.Status=status.Status;answer.Books=status.Books;answer.Health=status.Health;answer.AuthenticationContext=status.AuthenticationContext;answer.ServerUrl=status.ServerUrl;return answer;
}
if (message.Kind is "document" or "reconcile")
{
if (message.Documents == null || message.Documents.Length > ProtocolVersion.MaxDocuments || message.Documents.Any(d=>d==null) || message.Documents.Select(d => d.SessionId).Distinct().Count() != message.Documents.Length
|| message.Documents.Any(d => d.SessionId == Guid.Empty || d.ManuscriptId == Guid.Empty || d.Revision < 0 || d.ProjectId is <= 0 || d.BookId is <= 0 || d.ProjectId.HasValue != d.BookId.HasValue)) return Reject(answer,"invalid-documents");
if(message.Documents.Any(d=>instances.Any(i=>i.Key!=message.WordInstanceId&&i.Value.Documents.ContainsKey(d.SessionId))))return Reject(answer,"foreign-session-identity");
if (message.Kind == "reconcile")
{
foreach(var prior in word.Documents.Values)ClearDocument(prior); word.Documents.Clear(); word.ActiveSession = null;
}
foreach (var descriptor in message.Documents)
{
if (word.Documents.TryGetValue(descriptor.SessionId, out var existing))
{
if (descriptor.Revision < existing.Descriptor.Revision || descriptor.ManuscriptId != existing.Descriptor.ManuscriptId) return Reject(answer,"stale-document");
if (descriptor.Revision > existing.Descriptor.Revision) { ClearDocument(existing); }
existing.Descriptor = descriptor;
}
else
{
if (word.Documents.Count >= ProtocolVersion.MaxDocuments) return Reject(answer,"document-capacity");
word.Documents.Add(descriptor.SessionId, new DocumentState(descriptor));
}
}
return answer;
}
if (!word.Documents.TryGetValue(message.SessionId, out var document)) return Reject(answer,"unknown-session");
if (message.Kind == "close")
{
ClearDocument(document); word.Documents.Remove(message.SessionId);
if (word.ActiveSession == message.SessionId) word.ActiveSession = null;
return answer;
}
if (message.Revision != document.Descriptor.Revision) return Reject(answer,"stale-revision");
if(message.Kind.StartsWith("workspace-",StringComparison.Ordinal)){answer.Kind="workspace-response";answer.BookId=message.BookId;answer.AuthenticationContext=message.AuthenticationContext;
if(message.Kind=="workspace-preview"&&(message.ImportSelection?.SnapshotId!=document.SnapshotId||message.ImportSelection?.ManuscriptId!=document.Descriptor.ManuscriptId)){answer.ImportPreview=new(){RequestId=message.ImportSelection?.RequestId??Guid.Empty,State="rejected",Message="Document snapshot changed. Detect structure and preview again."};return Reject(answer,"stale-preview");}
if(message.Kind is "workspace-select" or "workspace-refresh"){var position=new Message();Resolve(document,position);message.ChapterId=position.ChapterId;message.SceneId=position.SceneId;}
answer.Kind="workspace-response";return workspace?.Handle(document.Descriptor,message,answer)??Reject(answer,"workspace-unavailable");}
if(message.Kind.StartsWith("ai-",StringComparison.Ordinal))return ai?.Handle(document.Descriptor,message,answer)??Reject(answer,"ai-unavailable");
switch (message.Kind)
{
case "metrics": break;
case "active": word.ActiveSession = message.SessionId; break;
case "selection":
if (message.Start < 0 || message.End < message.Start) return Reject(answer,"invalid-position");
document.Cursor = message.Start; Resolve(document, answer);workspace?.Position(message.SessionId,answer.ChapterId,answer.SceneId);break;
case "snapshot-begin":
if (message.SnapshotId == Guid.Empty || message.End < 0 || message.End > MaxSnapshotCharacters) return Reject(answer,"invalid-snapshot");
ClearPending(document);
document.Pending = new Snapshot(message.SnapshotId,message.End,message.RequestAnalysis); break;
case "snapshot-fragment":
var pending = document.Pending; var fragment = message.Fragment;
if (pending == null || pending.Id != message.SnapshotId) return Reject(answer,"obsolete-snapshot");
if (fragment == null || fragment.Text == null || fragment.Text.Length > ProtocolVersion.MaxParagraphCharacters || fragment.Start != pending.End || fragment.End <= fragment.Start || fragment.End>pending.ExpectedEnd || fragment.End-fragment.Start > ProtocolVersion.MaxParagraphCharacters || fragment.ParagraphIndex != pending.NextParagraph || fragment.OutlineLevel < 1 || fragment.OutlineLevel > 10
|| fragment.MarkerTags == null || fragment.MarkerTags.Length > 16 || fragment.MarkerTags.Any(t => t == null || t.Length > 128) || pending.Fragments.Count >= 200_000)
return Reject(answer,"invalid-fragment");
// Include marker text and a per-fragment metadata allowance so
// tiny paragraphs/large marker lists cannot bypass the global budget.
var cost = fragment.Text.Length + fragment.MarkerTags.Sum(t=>t.Length) + 128;
if (pending.Characters + cost > MaxSnapshotCharacters || totalCharacters + cost > MaxTotalCharacters || totalFragments >= 200_000) return Reject(answer,"snapshot-capacity");
pending.Characters += cost; totalCharacters += cost; totalFragments++;
pending.End = fragment.End; pending.LastComplete = fragment.CompletesParagraph; if(fragment.CompletesParagraph)pending.NextParagraph++; pending.Fragments.Add(fragment); pending.Analysis?.Add(fragment);
answer.Progress=pending.ExpectedEnd==0?100:(int)(100L*pending.End/pending.ExpectedEnd); break;
case "snapshot-end":
if (document.Pending == null || document.Pending.Id != message.SnapshotId) return Reject(answer,"obsolete-snapshot");
var snapshot = document.Pending;
if(snapshot.End != snapshot.ExpectedEnd || (snapshot.End > 0 && !snapshot.LastComplete)) return Reject(answer,"incomplete-snapshot");
var boundaries = StructuralParser.Parse(snapshot.Fragments);
if(boundaries.Count>8192 || totalBoundaries-document.Boundaries.Count+boundaries.Count>32768)return Reject(answer,"structure-capacity");
var suggestionCount = snapshot.Analysis?.Count ?? 0;
if(totalSuggestions-(document.Analysis?.Count??0)+suggestionCount>32768)return Reject(answer,"analysis-capacity");
totalSuggestions+=suggestionCount-(document.Analysis?.Count??0);
document.Analysis=snapshot.Analysis;
totalBoundaries += boundaries.Count-document.Boundaries.Count;
document.Boundaries = boundaries;
document.SnapshotId = snapshot.Id;
document.ContentFingerprint = StructuralParser.Fingerprint(snapshot.Fragments);
ClearPending(document); Resolve(document, answer);workspace?.Position(message.SessionId,answer.ChapterId,answer.SceneId);
if(document.Analysis!=null){answer.Analysis=document.Analysis.Page(0);answer.Status="analysis-complete";answer.Progress=100;}
break;
case "analysis-page":
if(document.SnapshotId!=message.SnapshotId||document.Analysis==null)return Reject(answer,"analysis-unavailable");
if(message.Start<0||message.Start>document.Analysis.Count)return Reject(answer,"invalid-page");
answer.Analysis=document.Analysis.Page(message.Start);answer.Status="analysis-complete";answer.Progress=100;break;
case "snapshot-cancel":
if (document.Pending?.Id == message.SnapshotId) { ClearPending(document); }
break;
default: return Reject(answer,"unsupported-operation");
}
return answer;
}
}
private static Message Reject(Message answer,string status) { answer.Status = status; return answer; }
private static void Resolve(DocumentState document, Message answer)
{
var boundary = document.Boundaries.LastOrDefault(b => b.Start <= document.Cursor);
if (boundary == null) { answer.Status = "awaiting-structure"; return; }
answer.ChapterId = boundary.ChapterId; answer.SceneId = boundary.SceneId;
answer.ChapterTitle = boundary.ChapterTitle; answer.SceneTitle = boundary.SceneTitle;
answer.SnapshotId = document.SnapshotId; answer.Revision = document.Descriptor.Revision;
}
public Guid? ActiveSession(Guid instance) { lock(gate) return instances.GetValueOrDefault(instance)?.ActiveSession; }
public bool HasSession(Guid instance, Guid session) { lock(gate) return instances.TryGetValue(instance,out var word) && word.Documents.ContainsKey(session); }
private sealed class WordInstance(Guid lease) { public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary<Guid,DocumentState> Documents = []; }
private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List<StructuralBoundary> Boundaries = []; public DocumentAnalysis? Analysis; }
private sealed class Snapshot(Guid id,int expectedEnd,bool analyze) { public DocumentAnalysis? Analysis=analyze?new DocumentAnalysis():null; public Guid Id = id; public int ExpectedEnd=expectedEnd; public bool LastComplete; public int End; public int NextParagraph=1; public int Characters; public List<ParagraphFragment> Fragments = []; }
}
public sealed record StructuralBoundary(int Start, int? ChapterId, int? SceneId, string ChapterTitle, string SceneTitle);
public static class StructuralParser
{
public static List<StructuralBoundary> Parse(IReadOnlyList<ParagraphFragment> fragments)
{
List<StructuralBoundary> result = []; int? chapterId = null; var chapterTitle = ""; var previousParagraph = -1;
foreach (var fragment in fragments)
{
if (fragment.ParagraphIndex == previousParagraph) continue;
previousParagraph = fragment.ParagraphIndex;
var chapter = MarkerId(fragment.MarkerTags,"PD-CHAPTER-"); var scene = MarkerId(fragment.MarkerTags,"PD-SCENE-");
if (fragment.OutlineLevel == 1 || chapter.HasValue)
{
chapterId = chapter; chapterTitle = Title(fragment.Text);
result.Add(new(fragment.Start,chapterId,scene,chapterTitle,scene.HasValue ? "Scene" : ""));
}
else if (fragment.OutlineLevel == 2 || scene.HasValue)
result.Add(new(fragment.Start,chapterId,scene,chapterTitle,fragment.OutlineLevel == 2 ? Title(fragment.Text) : "Scene"));
}
return result;
}
public static int? MarkerId(IEnumerable<string> tags,string prefix) => tags.Select(t=>t.Replace("_","-").TrimStart('-'))
.Where(t=>t.StartsWith(prefix,StringComparison.OrdinalIgnoreCase))
.Select(t=>int.TryParse(t[prefix.Length..],out var id)&&id>0?(int?)id:null).FirstOrDefault(id=>id.HasValue);
private static string Title(string value) {var title=value.Trim();return title.Length>200?title[..200]:title;}
public static string Fingerprint(IReadOnlyList<ParagraphFragment> fragments)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
foreach (var fragment in fragments) hash.AppendData(Encoding.UTF8.GetBytes(fragment.Text));
return Convert.ToHexString(hash.GetHashAndReset());
}
}