using System.Text; using PlotDirector.Companion.Protocol; namespace PlotDirector.Companion.Agent; // One explicit chapter upload per document. Never automatically replays a network submission. public sealed class ChapterAiWork(CloudGateway cloud):IDisposable { private readonly object gate=new(); private readonly Dictionary jobs=[]; public Message Handle(DocumentDescriptor descriptor,Message request,Message answer) { lock(gate) { if(request.Kind=="ai-begin") { if(!cloud.Allows(request.AuthenticationContext,request.BookId)){answer.Status="authentication-changed";return answer;} if(request.SnapshotId==Guid.Empty||request.BookId<=0||request.Start<0||request.End<=request.Start||request.End-request.Start>120000){answer.Status="invalid-ai-chapter";return answer;} if(!jobs.ContainsKey(descriptor.SessionId)&&jobs.Count>=32){answer.Status="ai-capacity";return answer;} Clear(descriptor.SessionId); var chapter=new AiChapterRequest{RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterTitle=request.ChapterTitle.Length<=200?request.ChapterTitle:request.ChapterTitle[..200],ChapterStart=request.Start,ChapterEnd=request.End}; jobs[descriptor.SessionId]=new(chapter,request.AuthenticationContext);return answer; } if(!jobs.TryGetValue(descriptor.SessionId,out var job)||job.Chapter.RequestId!=request.SnapshotId){answer.Status="obsolete-ai-request";return answer;} if(!cloud.Allows(job.AuthenticationContext,job.Chapter.BookId)){Clear(descriptor.SessionId);answer.Status="authentication-changed";return answer;} switch(request.Kind) { case "ai-fragment": var f=request.Fragment; if(job.Submitted||f==null||f.Text==null||f.Text.Length>ProtocolVersion.MaxParagraphCharacters||f.Start!=job.Position||f.End<=f.Start||f.End>job.Chapter.ChapterEnd||f.ParagraphIndex!=job.NextParagraph||job.Paragraphs.Count>=10000){answer.Status="invalid-ai-fragment";break;} if(job.Characters+f.Text.Length>120000){answer.Status="ai-chapter-too-large";break;} if(job.Text.Length==0)job.ParagraphStart=f.Start; job.Characters+=f.Text.Length;job.Text.Append(f.Text);job.Position=f.End; if(f.CompletesParagraph){job.Paragraphs.Add(new(){Index=job.NextParagraph,Start=job.ParagraphStart,End=f.End,Text=job.Text.ToString(),IsHeading=f.OutlineLevel is 1 or 2});job.Text.Clear();job.NextParagraph++;} answer.Progress=(int)(100L*(job.Position-job.Chapter.ChapterStart)/(job.Chapter.ChapterEnd-job.Chapter.ChapterStart));break; case "ai-submit": if(job.Submitted)break; if(job.Position!=job.Chapter.ChapterEnd||job.Text.Length!=0){answer.Status="incomplete-ai-chapter";break;} job.Submitted=true;job.Chapter.Paragraphs=job.Paragraphs.ToArray();job.Result.State="analysing"; _=Task.Run(async()=>{ AiChapterResult result; try{result=await cloud.Analyse(job.Chapter,job.Token,job.AuthenticationContext);} catch(OperationCanceledException){result=new(){RequestId=job.Chapter.RequestId,State="cancelled",Message="AI analysis cancelled."};} catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or System.Text.Json.JsonException) {result=new(){RequestId=job.Chapter.RequestId,State="failed",Message=e is InvalidOperationException?e.Message:"Connection failed. Outcome may be unknown; explicit retry may incur another AI charge."};} lock(gate){job.Result=result;job.Chapter.Paragraphs=[];job.Paragraphs.Clear();job.Finished=true;job.Stop.Dispose();} });break; case "ai-cancel": Clear(descriptor.SessionId);answer.Status="ai-cancelled";return answer; case "ai-status":break; default:answer.Status="unsupported-operation";break; } var offset=Math.Max(0,request.Start);var result=job.Result; answer.Ai=new(){RequestId=result.RequestId,State=result.State,Message=result.Message,Total=result.Scenes.Length,Offset=offset,ReviewPath=result.ReviewPath,Scenes=result.Scenes.Skip(offset).Take(ProtocolVersion.AnalysisPageSize).ToArray()}; return answer; } } public AiChapterResult? Result(Guid session){lock(gate)return jobs.GetValueOrDefault(session)?.Result;} public void Clear(Guid session) { lock(gate)if(jobs.Remove(session,out var job)){if(!job.Finished)job.Stop.Cancel();if(!job.Submitted){job.Finished=true;job.Stop.Dispose();}if(job.Submitted)_=cloud.CancelRemote(job.Chapter.RequestId);job.Paragraphs.Clear();} } public void Dispose(){lock(gate)foreach(var session in jobs.Keys.ToArray())Clear(session);} private sealed class Job { public Job(AiChapterRequest chapter,Guid context){AuthenticationContext=context;Chapter=chapter;Position=chapter.ChapterStart;Token=Stop.Token;Result.RequestId=chapter.RequestId;} public Guid AuthenticationContext;public AiChapterRequest Chapter;public CancellationTokenSource Stop=new(TimeSpan.FromMinutes(6));public CancellationToken Token {get;}public bool Submitted,Finished; public int Characters;public int Position,NextParagraph=1,ParagraphStart; public StringBuilder Text=new();public List Paragraphs=[]; public AiChapterResult Result=new(){State="reading"}; } }