51 lines
2.3 KiB
C#
51 lines
2.3 KiB
C#
using PlotDirector.Companion.Agent;
|
|
|
|
if (!OperatingSystem.IsWindows()) { Console.Error.WriteLine("The interactive Companion agent requires Windows. Run the portable test harness on Linux."); return 2; }
|
|
var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"PlotDirector","Companion");
|
|
Directory.CreateDirectory(directory);
|
|
// FileShare.None is held for process lifetime; no cross-thread named-mutex ownership.
|
|
FileStream singleton;
|
|
try { singleton = new FileStream(Path.Combine(directory,"agent-"+System.Diagnostics.Process.GetCurrentProcess().SessionId+".lock"),FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None); }
|
|
catch(IOException) { return 0; }
|
|
using(singleton)
|
|
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=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;
|
|
while(!shutdown.IsCancellationRequested)
|
|
{
|
|
await Task.Delay(TimeSpan.FromSeconds(15),shutdown.Token);
|
|
if(host.ActivePeers>0)lastPeer=DateTime.UtcNow;
|
|
else if(DateTime.UtcNow-lastPeer>TimeSpan.FromMinutes(5)){shutdown.Cancel();return;}
|
|
}
|
|
});
|
|
try {await serve;} finally {shutdown.Cancel();try{await idle;}catch(OperationCanceledException){}}
|
|
|
|
}
|
|
return 0;
|
|
|
|
sealed class AgentLog(string directory)
|
|
{
|
|
private readonly object gate = new();
|
|
public void Write(string message)
|
|
{
|
|
lock(gate)
|
|
{
|
|
try
|
|
{
|
|
var path=Path.Combine(directory,"agent.jsonl");
|
|
if(File.Exists(path)&&new FileInfo(path).Length>2*1024*1024)File.Move(path,path+".previous",true);
|
|
File.AppendAllText(path,System.Text.Json.JsonSerializer.Serialize(new{utc=DateTime.UtcNow,component="agent",message})+Environment.NewLine);
|
|
}
|
|
catch(IOException) { } catch(UnauthorizedAccessException) { }
|
|
}
|
|
}
|
|
}
|