using System.IO; using System.Diagnostics; using System.IO.Pipes; using System.Threading; using System.Threading.Tasks; using PlotDirector.Companion.Protocol; namespace PlotDirector.Companion.Client; public sealed class AgentLink : IDisposable { private sealed class ChapterWait { public readonly Stopwatch Wall=Stopwatch.StartNew();public int Polls;public double ExchangeMs,IdleMs; } private readonly Dictionary chapterWaits=new(); // Worker thread only, bounded by open-document capacity. public event Action? ChapterHandoff; private void EndChapterWait(Guid session,string reason) { if(!chapterWaits.TryGetValue(session,out var wait))return;chapterWaits.Remove(session); ChapterHandoff?.Invoke(new ChapterHandoffTiming{Session=session,Reason=reason,WallMs=wait.Wall.Elapsed.TotalMilliseconds,ExchangeMs=wait.ExchangeMs,IdleMs=wait.IdleMs,Polls=wait.Polls}); } private bool PollChapterCommands() { foreach(var session in chapterWaits.Where(p=>p.Value.Wall.ElapsedMilliseconds>=3000).Select(p=>p.Key).ToArray())EndChapterWait(session,"window-ended"); return chapterWaits.Count>0; } private readonly string pipeName; private readonly Guid instanceId; private readonly Func verifyServer; private readonly Action? startAgent; private readonly object gate = new(); private readonly Dictionary documents = new(); private readonly CancellationTokenSource stop = new(); private readonly BoundedMailbox mailbox = new(); private long sequence; private int disposed; private int resetRequested; private Task? worker; private DateTime lastLaunch; public int QueueDepth => mailbox.Depth; public event Action? Received; public event Action? StateChanged; public AgentLink(string pipeName, Guid instanceId, Func verifyServer, Action? startAgent = null) { this.pipeName = pipeName; this.instanceId = instanceId; this.verifyServer = verifyServer; this.startAgent = startAgent; } public void Start() { lock (gate) { if (worker == null) worker = Task.Run(RunAsync); } } public bool Register(DocumentDescriptor descriptor) { lock (gate) { if (!documents.ContainsKey(descriptor.SessionId) && documents.Count >= ProtocolVersion.MaxDocuments) return false; documents[descriptor.SessionId] = descriptor; } var accepted = TryPost(new Message { Kind = "document", Documents = new[] { descriptor } }); if (!accepted) Reset(); return accepted; } public void Retire(Guid sessionId) { lock (gate) documents.Remove(sessionId); // If lifecycle delivery is backpressured, force a reconciled connection. if (!TryPost(new Message { Kind = "close", SessionId = sessionId })) Reset(); } private NamedPipeClientStream? activePipe; public void Reset() { // Even handle cancellation/closure stays off the Office callback thread. if (Interlocked.Exchange(ref resetRequested,1) != 0) return; _ = Task.Run(() => { try { NamedPipeClientStream? pipe; lock (gate) pipe = activePipe; try { pipe?.Dispose(); } catch (IOException) { } } finally { Volatile.Write(ref resetRequested,0); } }); } public bool TryPost(Message message) { if (Volatile.Read(ref disposed) != 0 || stop.IsCancellationRequested) return false; message.WordInstanceId = instanceId; return mailbox.TryPost(message); } private Message Reconcile() { lock (gate) return new Message { Kind = "reconcile", WordInstanceId = instanceId, Sequence = Interlocked.Increment(ref sequence), Documents = documents.Values.ToArray() }; } private async Task ExchangeAsync(Stream pipe, Message message, CancellationToken cancellation) { var exchangeWatch=Stopwatch.StartNew(); using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation)) { timeout.CancelAfter(TimeSpan.FromSeconds(3)); if (message.Kind != "hello") message.Sequence = Interlocked.Increment(ref sequence); // Framework pipe cancellation can depend on the underlying operation. Closing // the pipe on expiry is the final bound, and runs off Word's UI thread. using (timeout.Token.Register(() => { try { pipe.Dispose(); } catch (IOException) { } })) { await FrameCodec.WriteAsync(pipe, message, timeout.Token).ConfigureAwait(false); var response = await FrameCodec.ReadAsync(pipe, timeout.Token).ConfigureAwait(false); if (response.CorrelationId != message.CorrelationId || response.Version != ProtocolVersion.Current) throw new InvalidDataException("IPC response identity/version mismatch."); if (response.Status == "unsupported-version" || (message.Kind == "hello" && (response.Status != "ready" || !ProtocolVersion.SupportsRequiredCapabilities(response.Capabilities)))) throw new InvalidDataException("Incompatible agent protocol/capabilities."); foreach(var wait in chapterWaits.Values)wait.ExchangeMs+=exchangeWatch.Elapsed.TotalMilliseconds; if(response.Command!=null)EndChapterWait(response.Command.SessionId,"next-command"); if(response.ChapterStatusProvided&&response.ChapterProgress?.State is "Synchronised" or "Needs review")EndChapterWait(response.SessionId,"terminal-status"); if(message.Kind is "tray-sync" or "tray-repair")response.Action=message.Kind; Received?.Invoke(response); } } } private async Task RunAsync() { var attempt = 0; while (!stop.IsCancellationRequested) { try { using (var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { lock (gate) activePipe = pipe; await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false); if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner."); await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability+","+ProtocolVersion.NativeChapterTextCapability+","+ProtocolVersion.NativeChapterPositionsCapability+","+ProtocolVersion.LiveChapterTextCapability }, stop.Token).ConfigureAwait(false); mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments. await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false); attempt = 0; StateChanged?.Invoke("connected"); var lastExchange = DateTime.UtcNow; while (!stop.IsCancellationRequested) { if (mailbox.TryTake(out var message)) { if(message!.Kind=="chapter-end"&&chapterWaits.Count=TimeSpan.FromMilliseconds(25)) { foreach(var wait in chapterWaits.Values)wait.Polls++; await ExchangeAsync(pipe,new Message{Kind="ping",WordInstanceId=instanceId},stop.Token).ConfigureAwait(false); lastExchange=DateTime.UtcNow; } else if (DateTime.UtcNow - lastExchange > TimeSpan.FromSeconds(1)) { await ExchangeAsync(pipe,new Message { Kind="ping", WordInstanceId=instanceId },stop.Token).ConfigureAwait(false); lastExchange = DateTime.UtcNow; } else { var idle=Stopwatch.StartNew();await Task.Delay(25,stop.Token).ConfigureAwait(false); foreach(var wait in chapterWaits.Values)wait.IdleMs+=idle.Elapsed.TotalMilliseconds; } } } } catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is TimeoutException || ex is OperationCanceledException || ex is UnauthorizedAccessException || ex is ObjectDisposedException || ex is System.Runtime.Serialization.SerializationException) { if (stop.IsCancellationRequested) break; StateChanged?.Invoke("offline"); if (DateTime.UtcNow - lastLaunch > TimeSpan.FromSeconds(30)) { lastLaunch = DateTime.UtcNow; try { startAgent?.Invoke(); } catch (Exception launchError) when (launchError is IOException || launchError is System.ComponentModel.Win32Exception || launchError is InvalidOperationException) { } } try { await Task.Delay(Math.Min(5000, 250 * ++attempt), stop.Token).ConfigureAwait(false); } catch (OperationCanceledException) { } } finally { chapterWaits.Clear();lock (gate) activePipe = null; } } } // Never join the worker from an Office callback or hold the Word thread for shutdown. public void Dispose() { if (Interlocked.Exchange(ref disposed,1) != 0) return; mailbox.Clear(); _ = Task.Run(() => { stop.Cancel(); Reset(); }); } public Task Completion => worker ?? Task.CompletedTask; } public sealed class ChapterHandoffTiming { public Guid Session{get;set;}public string Reason{get;set;}="";public double WallMs{get;set;}public double ExchangeMs{get;set;}public double IdleMs{get;set;}public int Polls{get;set;} }