feat: expose existing chapter AI through secure native companion pairing
This commit is contained in:
parent
76a92f9c65
commit
af243d3a9b
9
Docs/WordCompanion/2026-11-05-phase3-baseline.md
Normal file
9
Docs/WordCompanion/2026-11-05-phase3-baseline.md
Normal file
@ -0,0 +1,9 @@
|
||||
# Phase 3 baseline and milestones
|
||||
|
||||
The shared branch fast-forwarded cleanly from c1c6009 to 76a92f9 before work. Phase 1 Windows fixes are ancestors; the author reports live Phase 2 use with approximately 154,876 words, 48 local chapter and 309 local scene suggestions, with developer installation 1.0.0.4. The checked-in Windows checkpoint predates that live test. No Windows operation is possible on Atlas.
|
||||
|
||||
Existing `ManuscriptStructureAnalysisService.AnalyseChapterAsync` is the canonical chapter AI entry point used by `OnboardingService.AnalyseApprovedChaptersAsync`. It loads Chapter-Structure-Prompt-V2, uses the existing IStoryIntelligenceClient and configured ChapterStructureModel, canonical JSON repair/normalisation/validation and reversible paragraph maps. Native requests reuse it; there is no new AI engine or provider key in the agent. Web behavior remains on its original path.
|
||||
|
||||
Milestone 1 adds browser-approved short-lived desktop grants (existing cookie sign-in, antiforgery approval, verifier-bound one-use pairing, Data Protection, current database security-stamp checks), native-only authenticated chapter API, authorisation/subscription checks, bounded in-memory request deduplication/cancellation and agent-side HTTP/capture orchestration. Credentials remain only in agent memory; no browser cookies/passwords are exported. Native privacy mode suppresses raw chapter-response diagnostics. The provider client's failure logging no longer includes exception content that could contain provider response excerpts.
|
||||
|
||||
Later commits complete UI integration, Windows update/explicit per-user installation scripts and qualification evidence. The final report is authoritative for final verification and deployment state. An intermediate milestone is not a tested Windows installation.
|
||||
66
PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs
Normal file
66
PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs
Normal file
@ -0,0 +1,66 @@
|
||||
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<Guid,Job> jobs=[];
|
||||
public Message Handle(DocumentDescriptor descriptor,Message request,Message answer)
|
||||
{
|
||||
lock(gate)
|
||||
{
|
||||
if(request.Kind=="ai-begin")
|
||||
{
|
||||
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,ChapterStart=request.Start,ChapterEnd=request.End};
|
||||
jobs[descriptor.SessionId]=new(chapter);return answer;
|
||||
}
|
||||
if(!jobs.TryGetValue(descriptor.SessionId,out var job)||job.Chapter.RequestId!=request.SnapshotId){answer.Status="obsolete-ai-request";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()});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.Stop.Token);}
|
||||
catch(OperationCanceledException){result=new(){RequestId=job.Chapter.RequestId,State="cancelled",Message="AI analysis cancelled."};}
|
||||
catch(Exception e)when(e is HttpRequestException or IOException 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();}
|
||||
});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,Scenes=result.Scenes.Skip(offset).Take(ProtocolVersion.AnalysisPageSize).ToArray()};
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
public void Clear(Guid session)
|
||||
{
|
||||
lock(gate)if(jobs.Remove(session,out var job)){job.Stop.Cancel();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(AiChapterRequest chapter)
|
||||
{
|
||||
public AiChapterRequest Chapter=chapter;public CancellationTokenSource Stop=new(TimeSpan.FromMinutes(6));public bool Submitted;
|
||||
public int Characters;public int Position=chapter.ChapterStart,NextParagraph=1,ParagraphStart;
|
||||
public StringBuilder Text=new();public List<AiParagraph> Paragraphs=[];
|
||||
public AiChapterResult Result=new(){RequestId=chapter.RequestId,State="reading"};
|
||||
}
|
||||
}
|
||||
100
PlotDirector.NativeCompanion/Agent/CloudGateway.cs
Normal file
100
PlotDirector.NativeCompanion/Agent/CloudGateway.cs
Normal file
@ -0,0 +1,100 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
|
||||
// All browser launching, HTTP and credentials stay in the agent. Tokens are memory-only.
|
||||
public sealed class CloudGateway : IDisposable
|
||||
{
|
||||
private readonly object gate=new();
|
||||
private readonly HttpClient http;
|
||||
private readonly Action<string> openBrowser;
|
||||
private CancellationTokenSource? pairing;
|
||||
private Uri? origin;
|
||||
private string? token;
|
||||
private string state="Not signed in";
|
||||
private CompanionBook[] books=[];
|
||||
private readonly string? settingsPath;
|
||||
private static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web);
|
||||
public CloudGateway(HttpMessageHandler? handler=null,Action<string>? browser=null,string? settingsPath=null)
|
||||
{
|
||||
http=new(handler??new HttpClientHandler{AllowAutoRedirect=false}){Timeout=TimeSpan.FromMinutes(6)};
|
||||
openBrowser=browser??(url=>Process.Start(new ProcessStartInfo(url){UseShellExecute=true}));this.settingsPath=settingsPath;
|
||||
}
|
||||
public static Uri ValidateOrigin(string value)
|
||||
{
|
||||
if(!Uri.TryCreate(value,UriKind.Absolute,out var uri)||uri.Scheme!=Uri.UriSchemeHttps||!string.IsNullOrEmpty(uri.UserInfo)||uri.AbsolutePath!="/"||!string.IsNullOrEmpty(uri.Query)||!string.IsNullOrEmpty(uri.Fragment))throw new ArgumentException("Enter the HTTPS PlotDirector site root.");
|
||||
return uri;
|
||||
}
|
||||
public Message Status()
|
||||
{lock(gate)return new(){Status=state,Books=books,ServerUrl=origin?.AbsoluteUri??ReadOrigin()};}
|
||||
private string ReadOrigin(){try{return settingsPath!=null&&File.Exists(settingsPath)?File.ReadAllText(settingsPath):"";}catch(IOException){return "";}}
|
||||
public void Connect(string address)
|
||||
{
|
||||
var uri=ValidateOrigin(address);CancellationTokenSource stop;
|
||||
lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;token=null;books=[];state="Starting browser sign-in…";}
|
||||
_=Task.Run(async()=>{
|
||||
try
|
||||
{
|
||||
if(settingsPath!=null){Directory.CreateDirectory(Path.GetDirectoryName(settingsPath)!);await File.WriteAllTextAsync(settingsPath,uri.AbsoluteUri,stop.Token);}
|
||||
var verifier=Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
|
||||
using var start=await http.PostAsJsonAsync(new Uri(uri,"api/native-companion/pair"),new{challenge},stop.Token);start.EnsureSuccessStatusCode();
|
||||
var data=await start.Content.ReadFromJsonAsync<PairStart>(Json,stop.Token)??throw new InvalidDataException();
|
||||
if(data.Code==null||data.Code.Length!=24||!data.Code.All(Uri.IsHexDigit))throw new InvalidDataException();
|
||||
lock(gate)if(pairing==stop)state="Approve in browser · code "+data.Code[^6..];
|
||||
openBrowser(new Uri(uri,"native-companion/authorize?code="+data.Code).AbsoluteUri);
|
||||
while(!stop.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(2000,stop.Token);
|
||||
using var response=await http.PostAsJsonAsync(new Uri(uri,"api/native-companion/token"),new{code=data.Code,verifier},stop.Token);
|
||||
if(response.StatusCode==HttpStatusCode.Accepted)continue;
|
||||
response.EnsureSuccessStatusCode();var grant=await response.Content.ReadFromJsonAsync<TokenReply>(Json,stop.Token)??throw new InvalidDataException();
|
||||
using var request=new HttpRequestMessage(HttpMethod.Get,new Uri(uri,"api/native-companion/books"));request.Headers.Authorization=new("Bearer",grant.AccessToken);
|
||||
using var list=await http.SendAsync(request,stop.Token);list.EnsureSuccessStatusCode();
|
||||
var available=await list.Content.ReadFromJsonAsync<CompanionBook[]>(Json,stop.Token)??[];
|
||||
lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";}
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or JsonException or System.ComponentModel.Win32Exception or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
|
||||
{lock(gate)if(pairing==stop)state="Sign-in failed or expired. Check the site address and try Connect again.";}
|
||||
});
|
||||
}
|
||||
public void SignOut(){lock(gate){pairing?.Cancel();pairing=null;token=null;books=[];state="Not signed in";}}
|
||||
public async Task<AiChapterResult> Analyse(AiChapterRequest chapter,CancellationToken cancellation)
|
||||
{
|
||||
Uri site;string access;
|
||||
lock(gate){site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");}
|
||||
using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)};
|
||||
request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access);
|
||||
using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation);
|
||||
if(response.StatusCode==HttpStatusCode.Unauthorized){SignOut();throw new InvalidOperationException("Sign-in expired. Connect again.");}
|
||||
if(!response.IsSuccessStatusCode)throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."});
|
||||
// Bound server response before deserializing; never log a body/provider message.
|
||||
await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192];
|
||||
int count;while((count=await stream.ReadAsync(bytes,cancellation))>0){if(buffer.Length+count>1024*1024)throw new InvalidDataException("AI response too large.");buffer.Write(bytes,0,count);}
|
||||
buffer.Position=0;var result=await JsonSerializer.DeserializeAsync<AiChapterResult>(buffer,Json,cancellation)??throw new InvalidDataException();
|
||||
if(result.RequestId!=chapter.RequestId||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Start<chapter.ChapterStart||s.End>chapter.ChapterEnd||s.End<=s.Start||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping.");
|
||||
return result;
|
||||
}
|
||||
public async Task CancelRemote(Guid id)
|
||||
{
|
||||
try
|
||||
{
|
||||
Uri? site;string? access;lock(gate){site=origin;access=token;}if(site==null||access==null)return;
|
||||
using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(5));using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,$"api/native-companion/analysis/{id}/cancel"));request.Headers.Authorization=new("Bearer",access);
|
||||
using var response=await http.SendAsync(request,timeout.Token);
|
||||
}
|
||||
catch(Exception e)when(e is HttpRequestException or OperationCanceledException){ }
|
||||
}
|
||||
public void Dispose(){SignOut();http.Dispose();}
|
||||
private sealed record PairStart(string Code);
|
||||
private sealed record TokenReply(string AccessToken);
|
||||
}
|
||||
@ -17,6 +17,8 @@ public sealed class DocumentAnalysis
|
||||
private int words, paragraphs, paragraphStart, paragraphLength, outline;
|
||||
private string[] tags = [];
|
||||
private bool truncated;
|
||||
private int documentEnd;
|
||||
private StructureSuggestion? chapter;
|
||||
public int Count => suggestions.Count;
|
||||
public void Add(ParagraphFragment fragment)
|
||||
{
|
||||
@ -29,6 +31,7 @@ public sealed class DocumentAnalysis
|
||||
if(next&&!inWord)words++;
|
||||
inWord=next;
|
||||
}
|
||||
documentEnd=fragment.End;
|
||||
if(!fragment.CompletesParagraph)return;
|
||||
paragraphs++; inWord=false;
|
||||
var text=prefix.ToString().Trim('\r','\n','\a',' ','\t');
|
||||
@ -48,11 +51,17 @@ public sealed class DocumentAnalysis
|
||||
private void Suggest(string kind,string text,string confidence,string reason)
|
||||
{
|
||||
if(suggestions.Count==Limit){truncated=true;return;}
|
||||
suggestions.Add(new StructureSuggestion{Start=paragraphStart,Paragraph=paragraphs,Kind=kind,Title=text.Length>200?text[..200]:text,Confidence=confidence,Reason=reason});
|
||||
var suggestion=new StructureSuggestion{Start=paragraphStart,Paragraph=paragraphs,Kind=kind,Title=text.Length>200?text[..200]:text,Confidence=confidence,Reason=reason,Origin=reason.StartsWith("Existing PlotDirector")?"Existing marker":"Local structure"};
|
||||
if(kind=="Chapter"){if(chapter!=null)chapter.End=paragraphStart;chapter=suggestion;}
|
||||
if(chapter!=null){suggestion.ChapterStart=chapter.Start;suggestion.ChapterTitle=chapter.Title;}
|
||||
suggestions.Add(suggestion);
|
||||
}
|
||||
public AnalysisPage Page(int offset)
|
||||
{
|
||||
if(offset<0||offset>suggestions.Count)throw new ArgumentOutOfRangeException(nameof(offset));
|
||||
if(chapter!=null)chapter.End=documentEnd;
|
||||
var chapters=suggestions.Where(s=>s.Kind=="Chapter").ToDictionary(s=>s.Start);
|
||||
foreach(var item in suggestions.Skip(offset).Take(ProtocolVersion.AnalysisPageSize))if(chapters.TryGetValue(item.ChapterStart,out var parent))item.ChapterEnd=parent.End;
|
||||
return new AnalysisPage{Offset=offset,Total=suggestions.Count,WordCount=words,ParagraphCount=paragraphs,
|
||||
ChapterCount=suggestions.Count(s=>s.Kind=="Chapter"),SceneCount=suggestions.Count(s=>s.Kind=="Scene"),Truncated=truncated,
|
||||
Notice=words==0?"No manuscript words found.":"Local suggestions only. Unmarked prose may contain undetected scenes. Nothing has been imported or changed.",
|
||||
|
||||
@ -56,7 +56,7 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
|
||||
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="unsupported-version"},cancellation); return;
|
||||
}
|
||||
instance = hello.WordInstanceId; sessions.Attach(instance,lease);
|
||||
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability},cancellation);
|
||||
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability},cancellation);
|
||||
log?.Invoke("peer-connected");
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
{
|
||||
|
||||
@ -12,8 +12,10 @@ using(var shutdown = new CancellationTokenSource())
|
||||
{
|
||||
Console.CancelKeyPress += (_,e) => {e.Cancel=true;shutdown.Cancel();};
|
||||
var log = new AgentLog(directory);
|
||||
log.Write("agent-start protocol=1 authentication=unavailable publisher=Nick-Beckley");
|
||||
var host=new PipeHost(AgentEndpoint.CurrentUserPipeName(),new SessionManager(),log.Write);
|
||||
log.Write("agent-start protocol=1 authentication=browser-pairing publisher=Nick-Beckley");
|
||||
using var cloud=new CloudGateway(settingsPath:Path.Combine(directory,"server-url.txt"));
|
||||
using var ai=new ChapterAiWork(cloud);
|
||||
var host=new PipeHost(AgentEndpoint.CurrentUserPipeName(),new SessionManager(cloud,ai),log.Write);
|
||||
var serve=host.RunAsync(shutdown.Token);
|
||||
var idle=Task.Run(async()=>{
|
||||
var lastPeer=DateTime.UtcNow;
|
||||
|
||||
@ -4,7 +4,7 @@ using PlotDirector.Companion.Protocol;
|
||||
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
|
||||
public sealed class SessionManager
|
||||
public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai = null)
|
||||
{
|
||||
private readonly object gate = new();
|
||||
private readonly Dictionary<Guid, WordInstance> instances = [];
|
||||
@ -37,6 +37,7 @@ public sealed class SessionManager
|
||||
}
|
||||
private void ClearDocument(DocumentState document)
|
||||
{
|
||||
ai?.Clear(document.Descriptor.SessionId);
|
||||
totalSuggestions -= document.Analysis?.Count ?? 0;document.Analysis=null;
|
||||
ClearPending(document);totalBoundaries -= document.Boundaries.Count;document.Boundaries=[];
|
||||
}
|
||||
@ -49,10 +50,18 @@ public sealed class SessionManager
|
||||
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-connect" or "cloud-signout")
|
||||
{
|
||||
answer.Kind="cloud-status";if(cloud==null)return Reject(answer,"cloud-unavailable");
|
||||
try{if(message.Kind=="cloud-connect")cloud.Connect(message.ServerUrl);if(message.Kind=="cloud-signout"){ai?.Dispose();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.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;
|
||||
@ -81,6 +90,7 @@ public sealed class SessionManager
|
||||
return answer;
|
||||
}
|
||||
if (message.Revision != document.Descriptor.Revision) return Reject(answer,"stale-revision");
|
||||
if(message.Kind.StartsWith("ai-",StringComparison.Ordinal))return ai?.Handle(document.Descriptor,message,answer)??Reject(answer,"ai-unavailable");
|
||||
switch (message.Kind)
|
||||
{
|
||||
case "metrics": break;
|
||||
|
||||
@ -97,7 +97,7 @@ public sealed class AgentLink : IDisposable
|
||||
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 }, stop.Token).ConfigureAwait(false);
|
||||
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability }, 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");
|
||||
|
||||
39
PlotDirector.NativeCompanion/Protocol/AiContracts.cs
Normal file
39
PlotDirector.NativeCompanion/Protocol/AiContracts.cs
Normal file
@ -0,0 +1,39 @@
|
||||
using System.Runtime.Serialization;
|
||||
namespace PlotDirector.Companion.Protocol;
|
||||
|
||||
[DataContract]
|
||||
public sealed class AiChapterRequest
|
||||
{
|
||||
[DataMember] public Guid RequestId { get; set; }
|
||||
[DataMember] public int BookId { get; set; }
|
||||
[DataMember] public Guid ManuscriptId { get; set; }
|
||||
[DataMember] public Guid SessionId { get; set; }
|
||||
[DataMember] public long Revision { get; set; }
|
||||
[DataMember] public int ChapterStart { get; set; }
|
||||
[DataMember] public int ChapterEnd { get; set; }
|
||||
[DataMember] public AiParagraph[] Paragraphs { get; set; }=Array.Empty<AiParagraph>();
|
||||
}
|
||||
[DataContract]
|
||||
public sealed class AiParagraph
|
||||
{
|
||||
[DataMember] public int Index { get; set; }
|
||||
[DataMember] public int Start { get; set; }
|
||||
[DataMember] public int End { get; set; }
|
||||
[DataMember] public string Text { get; set; }="";
|
||||
}
|
||||
[DataContract]
|
||||
public sealed class AiChapterResult
|
||||
{
|
||||
[DataMember] public Guid RequestId { get; set; }
|
||||
[DataMember] public int Total { get; set; }
|
||||
[DataMember] public int Offset { get; set; }
|
||||
[DataMember] public string State { get; set; }="";
|
||||
[DataMember] public string Message { get; set; }="";
|
||||
[DataMember] public StructureSuggestion[] Scenes { get; set; }=Array.Empty<StructureSuggestion>();
|
||||
}
|
||||
[DataContract]
|
||||
public sealed class CompanionBook
|
||||
{
|
||||
[DataMember] public int BookId { get; set; }
|
||||
[DataMember] public string Title { get; set; }="";
|
||||
}
|
||||
@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol;
|
||||
public static class ProtocolVersion
|
||||
{
|
||||
public const int Current = 1;
|
||||
public const string ChapterAiCapability = "chapter-ai-v1";
|
||||
public const string AnalysisCapability = "structure-review-v1";
|
||||
public const int AnalysisPageSize = 40;
|
||||
public const int MaxFrameBytes = 256 * 1024;
|
||||
@ -42,6 +43,10 @@ public sealed class Message
|
||||
[DataMember] public int? SceneId { get; set; }
|
||||
[DataMember] public string ChapterTitle { get; set; } = "";
|
||||
[DataMember] public string SceneTitle { get; set; } = "";
|
||||
[DataMember] public string ServerUrl { get; set; } = "";
|
||||
[DataMember] public AiChapterResult? Ai { get; set; }
|
||||
[DataMember] public CompanionBook[] Books { get; set; } = Array.Empty<CompanionBook>();
|
||||
[DataMember] public int BookId { get; set; }
|
||||
[DataMember] public bool RequestAnalysis { get; set; }
|
||||
[DataMember] public AnalysisPage? Analysis { get; set; }
|
||||
[DataMember] public int Progress { get; set; }
|
||||
@ -102,6 +107,11 @@ public sealed class StructureSuggestion
|
||||
[DataMember] public int Start { get; set; }
|
||||
[DataMember] public int Paragraph { get; set; }
|
||||
[DataMember] public string Kind { get; set; } = "";
|
||||
[DataMember] public int End { get; set; }
|
||||
[DataMember] public string Origin { get; set; } = "Local";
|
||||
[DataMember] public int ChapterStart { get; set; } = -1;
|
||||
[DataMember] public int ChapterEnd { get; set; }
|
||||
[DataMember] public string ChapterTitle { get; set; } = "";
|
||||
[DataMember] public string Title { get; set; } = "";
|
||||
[DataMember] public string Confidence { get; set; } = "";
|
||||
[DataMember] public string Reason { get; set; } = "";
|
||||
|
||||
48
PlotLine.Tests/NativeCompanionTests.cs
Normal file
48
PlotLine.Tests/NativeCompanionTests.cs
Normal file
@ -0,0 +1,48 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
|
||||
internal static class NativeCompanionTests
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
void Check(bool value,string name){if(!value)throw new Exception(name);}
|
||||
var clock=new Clock();var pairing=new DesktopPairing(new EphemeralDataProtectionProvider(),clock);
|
||||
var verifier=new string('a',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
|
||||
var code=pairing.Start(challenge);
|
||||
Check(pairing.Redeem(code,verifier)==null,"Pairing needs browser approval");
|
||||
var stamp=Guid.NewGuid();Check(pairing.Approve(code,7,stamp),"First browser approval");Check(!pairing.Approve(code,9,Guid.NewGuid()),"Cannot change approved owner");
|
||||
Check(pairing.Redeem(code,new string('b',64))==null,"Wrong verifier refused");
|
||||
var token=pairing.Redeem(code,verifier)!;var grant=pairing.Read(token)!;
|
||||
Check(grant.UserId==7&&grant.Stamp==stamp&&pairing.Redeem(code,verifier)==null,"One-use code yields correct protected subject");
|
||||
Check(pairing.Read("tampered"+token)==null,"Tampered grant refused");clock.Now=clock.Now.AddHours(5);Check(pairing.Read(token)==null,"Expired grant refused");
|
||||
var expires=pairing.Start(challenge);clock.Now=clock.Now.AddMinutes(6);Check(!pairing.Approve(expires,7,stamp),"Expired browser request refused");
|
||||
var request=new AiChapterRequest{RequestId=Guid.NewGuid(),BookId=3,ManuscriptId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ChapterStart=100,ChapterEnd=135,Paragraphs=[new(){Index=1,Start=100,End=110,Text="First scene."},new(){Index=2,Start=110,End=111,Text="\r"},new(){Index=3,Start=111,End=135,Text="Second scene begins."}]};
|
||||
var mapped=NativeChapterMapping.Build(request);
|
||||
Check(mapped.ParagraphMap.Count==2&&mapped.ParagraphMap[1].WordParagraphIndex==3&&mapped.PrivateAnalysis,"Blank paragraphs retain reversible Word mapping and private logging");
|
||||
var chapterJson="""{"schemaVersion":"1.0","chapterSummary":"A transition between arrival and departure.","sceneBoundaries":[{"sceneNumber":1,"startParagraph":1,"endParagraph":1,"suggestedTitle":"Arrival","confidence":0.9,"reason":"Opening","structuralSummary":"The opening scene establishes a clear dramatic moment and situation for the characters."},{"sceneNumber":2,"startParagraph":2,"endParagraph":2,"suggestedTitle":"Departure","confidence":0.8,"reason":"Transition","structuralSummary":"The next scene shifts the dramatic situation to a new moment and a different goal."}]}""";
|
||||
var fake=new FakeStoryIntelligenceClient(System.Text.Json.JsonSerializer.Serialize(new{output=new[]{new{content=new[]{new{type="output_text",text=chapterJson}}}}}));
|
||||
var service=new ManuscriptStructureAnalysisService(new FakeStoryPromptRepository(),new FakeStoryPromptVersionService(),fake,new ChapterStructureValidator(),NullLogger<ManuscriptStructureAnalysisService>.Instance);
|
||||
var result=await service.AnalyseChapterAsync(mapped);
|
||||
Check(result.Success,result.ErrorMessage??"Existing chapter AI pipeline accepts native paragraph map");
|
||||
var answer=NativeChapterMapping.Map(request,result);
|
||||
Check(answer.Scenes.Length==2&&answer.Scenes[0].Start==100&&answer.Scenes[1].Start==111&&answer.Scenes[1].End==135&&answer.Scenes.All(s=>s.Origin=="AI"),"AI boundaries map to exact Word ranges with explicit origin");
|
||||
Check(fake.Prompts.Single().Contains("First scene.")&&fake.Prompts.Single().Contains("Second scene begins."),"Existing prompt receives one chapter");
|
||||
request.Paragraphs[1].Start=109;try{NativeChapterMapping.Build(request);throw new Exception("Accepted bad map");}catch(ArgumentException){}
|
||||
var cache=new NativeAnalysisCache(clock);var calls=0;var id=Guid.NewGuid();var done=new TaskCompletionSource<AiChapterResult>();
|
||||
var first=cache.Run(7,id,"same",_=>{calls++;return done.Task;});var duplicate=cache.Run(7,id,"same",_=>throw new Exception("duplicate"));
|
||||
Check(ReferenceEquals(first,duplicate)&&calls==1,"In-flight duplicate shares provider call");
|
||||
try{_ = cache.Run(7,id,"different",_=>done.Task);throw new Exception("Accepted changed request ID");}catch(ArgumentException){}
|
||||
try{_ = cache.Run(7,Guid.NewGuid(),"other",_=>done.Task);throw new Exception("Accepted concurrent chapter");}catch(InvalidOperationException){}
|
||||
done.SetResult(new(){RequestId=id,State="complete"});await first;
|
||||
Check((await cache.Run(7,id,"same",_=>throw new Exception())).State=="complete","Successful duplicate reuses result");
|
||||
var cancelId=Guid.NewGuid();var pending=cache.Run(7,cancelId,"cancel",async c=>{await Task.Delay(Timeout.Infinite,c);return new();});cache.Cancel(8,cancelId);Check(!pending.IsCompleted,"Other user's cancellation isolated");cache.Cancel(7,cancelId);Check((await pending).State=="cancelled","Cancellation isolated to owned chapter");
|
||||
Check((await cache.Run(7,Guid.NewGuid(),"fail",_=>throw new IOException())).State=="failed","One failed chapter isolated");
|
||||
Check((await cache.Run(7,id,"same",_=>throw new Exception())).State=="complete","Success survives another chapter's failure");
|
||||
}
|
||||
private sealed class Clock:TimeProvider{public DateTimeOffset Now=DateTimeOffset.UtcNow;public override DateTimeOffset GetUtcNow()=>Now;}
|
||||
}
|
||||
@ -122,8 +122,11 @@ if (args.Contains("--plot-lines"))
|
||||
return;
|
||||
}
|
||||
|
||||
if(args.Contains("--native-companion")){await NativeCompanionTests.Run();Console.WriteLine("PASS native desktop pairing, canonical chapter AI/mapping, idempotency and cancellation");return;}
|
||||
|
||||
var tests = new (string Name, Action Test)[]
|
||||
{
|
||||
("Native companion authentication, canonical AI mapping and isolated chapter retry", () => NativeCompanionTests.Run().GetAwaiter().GetResult()),
|
||||
("Solver never discards a corroborated concern or exhausts navigation before verification", WritingSolverDeadEndTests.Regression),
|
||||
("Solver result evidence covers all reachable diagnoses without changing Stage 1 semantics", WritingSolverResultTests.EditorialCoverage),
|
||||
("Solver result copy follows actual answers, intention, variants and revision", WritingSolverResultTests.ListeningAndVariants),
|
||||
|
||||
35
PlotLine/Controllers/NativeCompanionAuthController.cs
Normal file
35
PlotLine/Controllers/NativeCompanionAuthController.cs
Normal file
@ -0,0 +1,35 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Microsoft.AspNetCore.RateLimiting.EnableRateLimiting("native-pair")]
|
||||
public sealed class NativeCompanionAuthController(DesktopPairing pairing):Controller
|
||||
{
|
||||
[AllowAnonymous,HttpPost("api/native-companion/pair")]
|
||||
public IActionResult Start([FromBody] PairStart request)
|
||||
{
|
||||
Response.Headers.CacheControl="no-store";
|
||||
if(request==null)return BadRequest();
|
||||
try{return Ok(new{code=pairing.Start(request.Challenge??"")});}
|
||||
catch(ArgumentException){return BadRequest();}catch(InvalidOperationException){return StatusCode(429);}
|
||||
}
|
||||
[Authorize,HttpGet("native-companion/authorize")]
|
||||
public IActionResult Approve(string code)
|
||||
{Response.Headers.CacheControl="no-store";Response.Headers["Referrer-Policy"]="no-referrer";return !string.IsNullOrEmpty(code)&&pairing.Exists(code)?View("Approve",code):BadRequest("This request expired. Start Connect again in Word.");}
|
||||
[Authorize,HttpPost("native-companion/authorize"),ValidateAntiForgeryToken]
|
||||
public IActionResult ApproveGrant(string code)
|
||||
{
|
||||
if(string.IsNullOrEmpty(code))return BadRequest();
|
||||
if(!int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var user)||!Guid.TryParse(User.FindFirstValue("PlotLine.SecurityStamp"),out var stamp))return Forbid();
|
||||
Response.Headers.CacheControl="no-store";
|
||||
return pairing.Approve(code,user,stamp)?Content("Word Companion connected. You may close this tab. The grant expires in four hours; signing out in Word discards it."):BadRequest("This request expired or was already approved.");
|
||||
}
|
||||
[AllowAnonymous,HttpPost("api/native-companion/token")]
|
||||
public IActionResult Token([FromBody] PairRedeem request)
|
||||
{Response.Headers.CacheControl="no-store";if(request==null)return BadRequest();var token=pairing.Redeem(request.Code??"",request.Verifier??"");return token==null?Accepted(new{status="pending-or-expired"}):Ok(new{accessToken=token});}
|
||||
public sealed record PairStart(string Challenge);
|
||||
public sealed record PairRedeem(string Code,string Verifier);
|
||||
}
|
||||
48
PlotLine/Controllers/NativeCompanionController.cs
Normal file
48
PlotLine/Controllers/NativeCompanionController.cs
Normal file
@ -0,0 +1,48 @@
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.NativeCompanion;
|
||||
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")]
|
||||
public sealed class NativeCompanionController(IWordCompanionRepository repository,NativeAnalysisCache cache,IServiceScopeFactory scopes,IConfiguration configuration,ISubscriptionService subscriptions):ControllerBase
|
||||
{
|
||||
private int UserId=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
[HttpGet("books")]
|
||||
public async Task<IActionResult> Books()
|
||||
{
|
||||
var result=new List<CompanionBook>();
|
||||
foreach(var project in await repository.ListProjectsAsync(UserId))
|
||||
result.AddRange((await repository.ListBooksAsync(project.ProjectId,UserId)).Select(b=>new CompanionBook{BookId=b.BookId,Title=project.Title+" / "+b.DisplayTitle}));
|
||||
return Ok(result.Take(500));
|
||||
}
|
||||
[HttpPost("analyse-chapter"),RequestSizeLimit(2*1024*1024)]
|
||||
public async Task<IActionResult> Analyse(AiChapterRequest request)
|
||||
{
|
||||
if(!(await subscriptions.CanUseFeatureAsync(UserId,PlotLine.Models.SubscriptionFeature.StoryIntelligence)).Allowed)return Forbid();
|
||||
// Access is checked on every request, including an idempotent cache hit.
|
||||
if(await repository.GetBookStructureAsync(request.BookId,UserId)==null)return Forbid();
|
||||
try
|
||||
{
|
||||
var mapped=NativeChapterMapping.Build(request,Math.Clamp(configuration.GetValue("NativeCompanion:MaxChapterCharacters",120000),10000,500000));
|
||||
var hash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request)));
|
||||
var task=cache.Run(UserId,request.RequestId,hash,async cancellation=>{
|
||||
await using var scope=scopes.CreateAsyncScope();
|
||||
var result=await scope.ServiceProvider.GetRequiredService<IManuscriptStructureAnalysisService>().AnalyseChapterAsync(mapped,cancellation);
|
||||
return NativeChapterMapping.Map(request,result);
|
||||
});
|
||||
Response.Headers.CacheControl="no-store";
|
||||
return Ok(await task.WaitAsync(HttpContext.RequestAborted));
|
||||
}
|
||||
catch(ArgumentException e){return BadRequest(new{message=e.Message});}
|
||||
catch(InvalidOperationException){return StatusCode(429,new{message="Analysis capacity is busy. Retry later."});}
|
||||
}
|
||||
[HttpPost("analysis/{id:guid}/cancel")]
|
||||
public IActionResult Cancel(Guid id){cache.Cancel(UserId,id);return NoContent();}
|
||||
}
|
||||
@ -7,6 +7,10 @@
|
||||
<UserSecretsId>7ebffbd4-1a5b-4053-840e-b52f93e756b8</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../PlotDirector.NativeCompanion/Protocol/PlotDirector.Companion.Protocol.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Dapper" Version="2.1.79" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="7.0.1" />
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using PlotLine.Data;
|
||||
@ -91,6 +92,11 @@ public class Program
|
||||
}
|
||||
};
|
||||
});
|
||||
builder.Services.AddRateLimiter(options => options.AddPolicy("native-pair", context => System.Threading.RateLimiting.RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new System.Threading.RateLimiting.FixedWindowRateLimiterOptions { PermitLimit=120, Window=TimeSpan.FromMinutes(1), QueueLimit=0 })));
|
||||
builder.Services.AddSingleton(TimeProvider.System);
|
||||
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.DesktopPairing>();
|
||||
builder.Services.AddAuthentication().AddScheme<Microsoft.AspNetCore.Authentication.AuthenticationSchemeOptions, PlotLine.Services.NativeCompanion.DesktopAuthentication>(PlotLine.Services.NativeCompanion.DesktopPairing.Scheme, _ => { });
|
||||
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.NativeAnalysisCache>();
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddPolicy("AdminOnly", policy =>
|
||||
@ -334,6 +340,7 @@ public class Program
|
||||
app.UseWritingSolverReviewBoundary();
|
||||
app.UseRouting();
|
||||
|
||||
app.UseRateLimiter();
|
||||
app.UseSession();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
@ -79,7 +79,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
|
||||
if (parseResult.Warnings.Count > 0)
|
||||
{
|
||||
logger.LogWarning(
|
||||
if (!request.PrivateAnalysis) logger.LogWarning(
|
||||
"Repaired structural scene-boundary JSON. ProjectID={ProjectID} BookID={BookID} PreviewID={PreviewID} TemporaryChapterKey={TemporaryChapterKey} SourceLabel={SourceLabel} ParserFailure={ParserFailure} DiagnosticExcerpt={DiagnosticExcerpt} RepairSucceeded={RepairSucceeded} RetryAttempted={RetryAttempted} Warnings={Warnings}",
|
||||
request.ProjectID,
|
||||
request.BookID,
|
||||
@ -101,7 +101,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
ChapterStructureBoundaryNormaliser.AddIssuesTo(validation, normalisation);
|
||||
if (normalisation.Issues.Count > 0)
|
||||
{
|
||||
logger.LogWarning(
|
||||
if (!request.PrivateAnalysis) logger.LogWarning(
|
||||
"Structural scene-boundary normalisation warnings. ProjectID={ProjectID} BookID={BookID} PreviewID={PreviewID} TemporaryChapterKey={TemporaryChapterKey} StructuralParagraphCount={StructuralParagraphCount} Warnings={Warnings}",
|
||||
request.ProjectID,
|
||||
request.BookID,
|
||||
@ -118,7 +118,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
if (!validation.IsValid || chapter?.SceneBoundaries is null || chapter.SceneBoundaries.Count == 0)
|
||||
{
|
||||
var diagnostic = BuildBoundaryDiagnostic(chapter, request.ParagraphMap, paragraphs.Count);
|
||||
logger.LogWarning(
|
||||
if (!request.PrivateAnalysis) logger.LogWarning(
|
||||
"Structural scene-boundary validation failed. ProjectID={ProjectID} BookID={BookID} TemporaryChapterKey={TemporaryChapterKey} StructuralParagraphCount={StructuralParagraphCount} Diagnostic={Diagnostic}",
|
||||
request.ProjectID,
|
||||
request.BookID,
|
||||
@ -192,7 +192,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
}
|
||||
|
||||
var rawPov = CleanPovSuggestion(chapter.DefaultPov);
|
||||
logger.LogInformation(
|
||||
if (!request.PrivateAnalysis) logger.LogInformation(
|
||||
"Structural POV audit. ProjectID={ProjectID} BookID={BookID} PreviewID={PreviewID} TemporaryChapterKey={TemporaryChapterKey} ExplicitNarrator={ExplicitNarrator} AiDefaultPov={AiDefaultPov} MixedPov={MixedPov} RawStructuralJson={RawStructuralJson}",
|
||||
request.ProjectID,
|
||||
request.BookID,
|
||||
@ -203,7 +203,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
chapter.MixedPov,
|
||||
parseResult.RawJson);
|
||||
|
||||
logger.LogInformation(
|
||||
if (!request.PrivateAnalysis) logger.LogInformation(
|
||||
"Structural scene-boundary analysis completed. ProjectID={ProjectID} BookID={BookID} TemporaryChapterKey={TemporaryChapterKey} Scenes={SceneCount}",
|
||||
request.ProjectID,
|
||||
request.BookID,
|
||||
@ -222,7 +222,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogWarning(
|
||||
if (!request.PrivateAnalysis) logger.LogWarning(
|
||||
ex,
|
||||
"Structural scene-boundary analysis failed. ProjectID={ProjectID} BookID={BookID} TemporaryChapterKey={TemporaryChapterKey}",
|
||||
request.ProjectID,
|
||||
@ -239,7 +239,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
bool retryAttempted)
|
||||
{
|
||||
var parserFailure = parseResult.InitialErrorMessage ?? parseResult.ErrorMessage;
|
||||
logger.LogWarning(
|
||||
if (!request.PrivateAnalysis) logger.LogWarning(
|
||||
"Structural scene-boundary JSON parse failed. ProjectID={ProjectID} BookID={BookID} PreviewID={PreviewID} TemporaryChapterKey={TemporaryChapterKey} SourceLabel={SourceLabel} ParserFailure={ParserFailure} DiagnosticExcerpt={DiagnosticExcerpt} RepairSucceeded={RepairSucceeded} RetryAttempted={RetryAttempted}",
|
||||
request.ProjectID,
|
||||
request.BookID,
|
||||
@ -684,6 +684,7 @@ public sealed partial class ManuscriptStructureAnalysisService(
|
||||
|
||||
public sealed class ManuscriptStructureAnalysisRequest
|
||||
{
|
||||
public bool PrivateAnalysis { get; init; }
|
||||
public int ProjectID { get; init; }
|
||||
public int BookID { get; init; }
|
||||
public Guid PreviewID { get; init; }
|
||||
|
||||
68
PlotLine/Services/NativeCompanion/DesktopPairing.cs
Normal file
68
PlotLine/Services/NativeCompanion/DesktopPairing.cs
Normal file
@ -0,0 +1,68 @@
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using PlotLine.Data;
|
||||
|
||||
namespace PlotLine.Services.NativeCompanion;
|
||||
|
||||
// Short lived, browser-approved desktop grants. No password/cookie export or refresh secret.
|
||||
public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvider clock)
|
||||
{
|
||||
public const string Scheme="NativeCompanion";
|
||||
private readonly IDataProtector protector=protection.CreateProtector("PlotDirector.NativeCompanion.Access.v1");
|
||||
private readonly object gate=new();
|
||||
private readonly Dictionary<string,Pending> pending=[];
|
||||
public string Start(string challenge)
|
||||
{
|
||||
if(challenge.Length!=64||!challenge.All(Uri.IsHexDigit))throw new ArgumentException("Invalid pairing challenge.");
|
||||
lock(gate)
|
||||
{
|
||||
foreach(var key in pending.Where(p=>p.Value.Expires<clock.GetUtcNow()).Select(p=>p.Key).ToArray())pending.Remove(key);
|
||||
if(pending.Count>=100)throw new InvalidOperationException("Pairing busy. Try later.");
|
||||
var code=Convert.ToHexString(RandomNumberGenerator.GetBytes(12));
|
||||
pending[code]=new(challenge,clock.GetUtcNow().AddMinutes(5));return code;
|
||||
}
|
||||
}
|
||||
public bool Exists(string code){lock(gate)return pending.TryGetValue(code,out var p)&&p.Expires>clock.GetUtcNow()&&p.UserId==null;}
|
||||
public bool Approve(string code,int userId,Guid stamp)
|
||||
{lock(gate){if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||p.UserId!=null)return false;p.UserId=userId;p.Stamp=stamp;return true;}}
|
||||
public string? Redeem(string code,string verifier)
|
||||
{
|
||||
if(verifier.Length<43||verifier.Length>128)return null;
|
||||
lock(gate)
|
||||
{
|
||||
if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(p.Challenge),Encoding.ASCII.GetBytes(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))))))return null;
|
||||
if(p.UserId is not int user)return null;
|
||||
pending.Remove(code);
|
||||
return protector.Protect(JsonSerializer.Serialize(new Grant(user,p.Stamp,clock.GetUtcNow().AddHours(4))));
|
||||
}
|
||||
}
|
||||
public Grant? Read(string token)
|
||||
{
|
||||
try{var grant=JsonSerializer.Deserialize<Grant>(protector.Unprotect(token));return grant?.Expires>clock.GetUtcNow()?grant:null;}
|
||||
catch(Exception e)when(e is CryptographicException or JsonException or FormatException){return null;}
|
||||
}
|
||||
public sealed record Grant(int UserId,Guid Stamp,DateTimeOffset Expires);
|
||||
private sealed class Pending(string challenge,DateTimeOffset expires){public string Challenge=challenge;public DateTimeOffset Expires=expires;public int? UserId;public Guid Stamp;}
|
||||
}
|
||||
|
||||
public sealed class DesktopAuthentication(IOptionsMonitor<AuthenticationSchemeOptions> options,ILoggerFactory logger,UrlEncoder encoder,DesktopPairing pairing,IUserRepository users)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options,logger,encoder)
|
||||
{
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var header=Request.Headers.Authorization.ToString();
|
||||
if(!header.StartsWith("Bearer ",StringComparison.OrdinalIgnoreCase))return AuthenticateResult.NoResult();
|
||||
if(header.Length>8192)return AuthenticateResult.Fail("Invalid grant.");
|
||||
var grant=pairing.Read(header[7..]);if(grant==null)return AuthenticateResult.Fail("Sign in again.");
|
||||
var user=await users.GetByIdAsync(grant.UserId);
|
||||
if(user==null||user.SecurityStamp!=grant.Stamp||(user.IsLocked&&(!user.LockoutEndUtc.HasValue||user.LockoutEndUtc>DateTime.UtcNow)))return AuthenticateResult.Fail("Sign in again.");
|
||||
var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString())],DesktopPairing.Scheme);
|
||||
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),DesktopPairing.Scheme));
|
||||
}
|
||||
}
|
||||
32
PlotLine/Services/NativeCompanion/NativeAnalysisCache.cs
Normal file
32
PlotLine/Services/NativeCompanion/NativeAnalysisCache.cs
Normal file
@ -0,0 +1,32 @@
|
||||
using PlotDirector.Companion.Protocol;
|
||||
namespace PlotLine.Services.NativeCompanion;
|
||||
|
||||
// Bounded process-local idempotency. Restart loses cache: agent never auto-replays after restart.
|
||||
public sealed class NativeAnalysisCache(TimeProvider clock)
|
||||
{
|
||||
private readonly object gate=new();
|
||||
private readonly Dictionary<(int,Guid),Entry> jobs=[];
|
||||
private readonly SemaphoreSlim workers=new(2);
|
||||
public Task<AiChapterResult> Run(int user,Guid id,string hash,Func<CancellationToken,Task<AiChapterResult>> work)
|
||||
{
|
||||
lock(gate)
|
||||
{
|
||||
foreach(var key in jobs.Where(j=>j.Value.Task.IsCompleted&&j.Value.Expires<clock.GetUtcNow()).Select(j=>j.Key).ToArray()){jobs[key].Stop.Dispose();jobs.Remove(key);}
|
||||
if(jobs.TryGetValue((user,id),out var prior))
|
||||
{if(prior.Hash!=hash)throw new ArgumentException("Request ID content mismatch.");return prior.Task;}
|
||||
if(jobs.Count>=256||jobs.Count(j=>j.Key.Item1==user&&!j.Value.Task.IsCompleted)>=1)throw new InvalidOperationException("Analysis busy. Wait for the current chapter.");
|
||||
var stop=new CancellationTokenSource(TimeSpan.FromMinutes(5));
|
||||
var entry=new Entry(hash,clock.GetUtcNow().AddMinutes(30),stop);
|
||||
jobs.Add((user,id),entry);entry.Task=Execute();return entry.Task;
|
||||
async Task<AiChapterResult> Execute()
|
||||
{
|
||||
try{await workers.WaitAsync(stop.Token);try{return await work(stop.Token);}finally{workers.Release();}}
|
||||
catch(OperationCanceledException){return new(){RequestId=id,State="cancelled",Message="Chapter analysis cancelled or timed out."};}
|
||||
catch(Exception){return new(){RequestId=id,State="failed",Message="Chapter analysis failed. Check server configuration or try this chapter again."};}
|
||||
}
|
||||
}
|
||||
}
|
||||
public void Cancel(int user,Guid id){lock(gate){if(jobs.TryGetValue((user,id),out var job))job.Stop.Cancel();}}
|
||||
private sealed class Entry(string hash,DateTimeOffset expires,CancellationTokenSource stop)
|
||||
{public string Hash=hash;public DateTimeOffset Expires=expires;public CancellationTokenSource Stop=stop;public Task<AiChapterResult> Task=System.Threading.Tasks.Task.FromResult(new AiChapterResult());}
|
||||
}
|
||||
40
PlotLine/Services/NativeCompanion/NativeChapterMapping.cs
Normal file
40
PlotLine/Services/NativeCompanion/NativeChapterMapping.cs
Normal file
@ -0,0 +1,40 @@
|
||||
using PlotDirector.Companion.Protocol;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services.NativeCompanion;
|
||||
|
||||
public static class NativeChapterMapping
|
||||
{
|
||||
public static ManuscriptStructureAnalysisRequest Build(AiChapterRequest request,int maxCharacters=120000)
|
||||
{
|
||||
if(request.RequestId==Guid.Empty||request.ManuscriptId==Guid.Empty||request.SessionId==Guid.Empty||request.BookId<=0||request.Revision<0||request.Paragraphs==null||request.Paragraphs.Length is <1 or >10000||request.ChapterStart<0||request.ChapterEnd<=request.ChapterStart)throw new ArgumentException("Invalid chapter identity or range.");
|
||||
var end=request.ChapterStart;var previousIndex=-1;var characters=0;
|
||||
foreach(var p in request.Paragraphs)
|
||||
{
|
||||
if(p==null||p.Text==null||p.Text.Length>maxCharacters||p.Index<=previousIndex||p.Start!=end||p.End<=p.Start||p.End>request.ChapterEnd)throw new ArgumentException("Invalid chapter paragraph mapping.");
|
||||
characters+=p.Text.Length;if(characters>maxCharacters)throw new ArgumentException("Chapter exceeds configured analysis size. Split or review its boundaries.");
|
||||
previousIndex=p.Index;end=p.End;
|
||||
}
|
||||
if(end!=request.ChapterEnd)throw new ArgumentException("Incomplete chapter.");
|
||||
var readable=request.Paragraphs.Where(p=>!string.IsNullOrWhiteSpace(p.Text.Trim('\a','\r','\n'))).ToArray();
|
||||
if(readable.Length==0)throw new ArgumentException("This chapter contains no readable paragraphs.");
|
||||
return new(){BookID=request.BookId,PreviewID=request.RequestId,TemporaryChapterKey=request.RequestId.ToString("N"),ChapterNumber=1,SourceLabel="Native Word chapter",PrivateAnalysis=true,
|
||||
ChapterText=string.Join("\n\n",readable.Select(p=>p.Text)),
|
||||
ParagraphMap=readable.Select((p,i)=>new ManuscriptScanParagraphMap{StructuralParagraphOrdinal=i+1,WordParagraphIndex=p.Index,Text=p.Text}).ToArray(),
|
||||
SourceParagraphs=request.Paragraphs.Select(p=>new ManuscriptScanSourceParagraph{WordParagraphIndex=p.Index,Text=p.Text,IsBlank=string.IsNullOrWhiteSpace(p.Text),IncludeInSourceText=true}).ToArray()};
|
||||
}
|
||||
public static AiChapterResult Map(AiChapterRequest request,ManuscriptStructureAnalysisResult result)
|
||||
{
|
||||
if(!result.Success)return new(){RequestId=request.RequestId,State="failed",Message="AI could not produce valid scene boundaries. Review the chapter or try again."};
|
||||
if(result.Scenes.Count>500)throw new ArgumentException("Too many scenes in one chapter.");
|
||||
var scenes=new List<StructureSuggestion>();
|
||||
foreach(var scene in result.Scenes)
|
||||
{
|
||||
var start=request.Paragraphs.FirstOrDefault(p=>p.Index==scene.WordStartPosition);
|
||||
var end=request.Paragraphs.FirstOrDefault(p=>p.Index==scene.WordEndPosition);
|
||||
if(start==null||end==null||end.End<=start.Start)throw new ArgumentException("AI scene could not be mapped to Word.");
|
||||
string Bound(string? text,int length)=>string.IsNullOrEmpty(text)?"":text.Length<=length?text:text[..length];
|
||||
scenes.Add(new(){Kind="Scene",Origin="AI",Start=start.Start,End=end.End,Paragraph=start.Index,Title=Bound(scene.Title,200),Reason=Bound(scene.Reason??scene.StructuralSummary,600),Confidence=scene.Confidence?.ToString("0.00",System.Globalization.CultureInfo.InvariantCulture)??"Unspecified"});
|
||||
}
|
||||
return new(){RequestId=request.RequestId,State="complete",Message="AI suggestions only. Manuscript and existing markers are unchanged.",Scenes=scenes.ToArray()};
|
||||
}
|
||||
}
|
||||
@ -256,7 +256,6 @@ public sealed class StoryIntelligenceClient(
|
||||
{
|
||||
stopwatch.Stop();
|
||||
logger.LogError(
|
||||
ex,
|
||||
"Story Intelligence prompt failed. PromptVersion={PromptVersion} Model={Model} DurationMs={DurationMs} RetryCount={RetryCount} InputTokens={InputTokens} OutputTokens={OutputTokens} EstimatedCost={EstimatedCost} Success={Success}",
|
||||
promptVersion,
|
||||
model,
|
||||
|
||||
12
PlotLine/Views/NativeCompanionAuth/Approve.cshtml
Normal file
12
PlotLine/Views/NativeCompanionAuth/Approve.cshtml
Normal file
@ -0,0 +1,12 @@
|
||||
@model string
|
||||
@{ ViewData["Title"] = "Connect Word Companion"; }
|
||||
<div class="container py-4" style="max-width:45rem">
|
||||
<h1>Connect Word Companion</h1>
|
||||
<p>Approve only if you just chose Connect in your own Word Companion. This grants access to your available books and allows chapter text you explicitly submit to use PlotDirector's configured AI provider.</p>
|
||||
<p>No manuscript is uploaded by signing in. The connection expires after four hours.</p>
|
||||
<form method="post" action="/native-companion/authorize">
|
||||
@Html.AntiForgeryToken()
|
||||
<input type="hidden" name="code" value="@Model" />
|
||||
<button type="submit" class="btn btn-primary">Approve this Word Companion connection</button>
|
||||
</form>
|
||||
</div>
|
||||
Loading…
x
Reference in New Issue
Block a user