RynthCore/src/RynthCore.StatusAgent/AgentConfig.cs
BlankenshipG c825406eed Merge rynth/main (2026.10.8.2) into sk/features-on-rynth-main
Resolves the conflicts that kept PR #2 from merging. Where rynth/main
already ships the same feature, its version wins: the shared read-only
RynthInstallPaths, chat match modes and standard filters, ItemInfoOnSelect
and merge-on-save for engine.json. The installer plugin hand-off moves to a
launcher-only InstallerHandoff helper; LoggingLevel stays launcher-owned.

See Changelog/2026-10-08-merge-rynth-main-into-pr2.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 22:11:03 -04:00

170 lines
9.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text.Json;
using System.Text.Json.Serialization;
using RynthCore.Install;
namespace RynthCore.StatusAgent;
/// <summary>
/// Agent configuration, loaded from %APPDATA%\RynthCore\statusagent.json.
/// The agent writes a commented template here on first run and never sends
/// anything until <see cref="Endpoint"/> is set to a non-empty URL.
/// </summary>
internal sealed class AgentConfig
{
/// <summary>Backend URL the agent POSTs the status payload to. EMPTY = the
/// agent never opens a network connection (local print-only mode).</summary>
[JsonPropertyName("Endpoint")] public string Endpoint { get; set; } = "";
/// <summary>Optional auth header sent with each POST (e.g. "Authorization").</summary>
[JsonPropertyName("AuthHeaderName")] public string AuthHeaderName { get; set; } = "Authorization";
/// <summary>Value for <see cref="AuthHeaderName"/> (e.g. "Bearer &lt;token&gt;"). Empty = no header.</summary>
[JsonPropertyName("AuthHeaderValue")] public string AuthHeaderValue { get; set; } = "";
/// <summary>Seconds between status posts.</summary>
[JsonPropertyName("IntervalSeconds")] public int IntervalSeconds { get; set; } = 5;
/// <summary>HTTP request timeout in seconds.</summary>
[JsonPropertyName("TimeoutSeconds")] public int TimeoutSeconds { get; set; } = 15;
/// <summary>Directory holding the engine's per-client status files.</summary>
[JsonPropertyName("StatusDirectory")] public string StatusDirectory { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreLogsDir, "status");
/// <summary>Directory holding per-client RynthCore.&lt;pid&gt;.log files (heartbeat fallback).</summary>
[JsonPropertyName("LogDirectory")] public string LogDirectory { get; set; } = RynthCore.Install.RynthInstallPaths.CoreLogsDir;
/// <summary>When true and no status file exists for a running client, derive
/// basic status from that client's heartbeat log line. Lets the agent work
/// even if EnableStatusExport is off (you just don't get bot/macro detail).</summary>
[JsonPropertyName("UseHeartbeatLogFallback")] public bool UseHeartbeatLogFallback { get; set; } = true;
/// <summary>A live-PID client whose snapshot is older than this is reported "hung".</summary>
[JsonPropertyName("StaleAfterSeconds")] public int StaleAfterSeconds { get; set; } = 12;
/// <summary>A dead-PID status file older than this is reported once then deleted.</summary>
[JsonPropertyName("DropDeadAfterSeconds")] public int DropDeadAfterSeconds { get; set; } = 300;
/// <summary>Label for this machine in the payload. Empty = use the machine name.</summary>
[JsonPropertyName("Host")] public string Host { get; set; } = "";
// ── Pull delivery: let an app fetch status instead of (or as well as) POST ──
/// <summary>When true, the agent serves the latest status at GET /status on
/// <see cref="ServePrefix"/> so an app can pull it with no backend. Default
/// false — no socket is opened unless you turn this on.</summary>
[JsonPropertyName("ServeHttp")] public bool ServeHttp { get; set; } = false;
/// <summary>HttpListener prefix to serve on. 127.0.0.1 = this PC only (no
/// admin needed). Use http://+:8740/ for LAN/Tailscale (needs a one-time
/// netsh urlacl or running elevated). Must end in '/'.</summary>
[JsonPropertyName("ServePrefix")] public string ServePrefix { get; set; } = "http://127.0.0.1:8740/";
/// <summary>Shared secret, required when <see cref="ServeHttp"/> is on: every route but
/// /healthz needs <c>Authorization: Bearer &lt;token&gt;</c> or <c>?token=</c>. Empty =
/// the server stays off, on any bind (it can stream the screens and click in them).</summary>
[JsonPropertyName("ServeToken")] public string ServeToken { get; set; } = "";
/// <summary>When true, also write the latest rollup to
/// Logs\status\aggregate.json — handy for file-sync delivery or debugging.</summary>
[JsonPropertyName("WriteAggregateFile")] public bool WriteAggregateFile { get; set; } = true;
/// <summary>When true, the agent accepts <c>POST /command</c> and writes a command file the
/// RynthAi plugin polls + applies (toggle nav/combat, start/stop, switch profile, clear busy).
/// Default FALSE — read-only unless you opt in. POST honours <see cref="ServeToken"/> like GET.
/// Commands are written under <see cref="StatusDirectory"/>\commands.</summary>
[JsonPropertyName("EnableRemoteControl")] public bool EnableRemoteControl { get; set; } = false;
/// <summary>When true, the agent serves a live screen capture of an AC client window:
/// <c>GET /stream?pid=N</c> (MJPEG) and <c>GET /frame?pid=N</c> (single JPEG). Captures the
/// window's on-screen rectangle ONLY while a client is connected — no cost otherwise. Default
/// FALSE. Honours <see cref="ServeToken"/>. Only captures windows that are actually rendering
/// (visible/restored — a minimized client has no frame).</summary>
[JsonPropertyName("EnableScreenStream")] public bool EnableScreenStream { get; set; } = false;
/// <summary>JPEG quality (1–100) and target frame interval (ms) for the screen stream.</summary>
[JsonPropertyName("StreamQuality")] public int StreamQuality { get; set; } = 55;
[JsonPropertyName("StreamIntervalMs")] public int StreamIntervalMs { get; set; } = 400;
/// <summary>HD video mode (WebRTC H.264). Opt-in, default FALSE. Adds POST /webrtc/offer + /webrtc/stop
/// (token-gated); captures+encodes a pid's window ONLY while a viewer is connected. Heavier than the
/// MJPEG stream (a per-pid ffmpeg encoder) — leave off unless you want the low-latency "HD" view.</summary>
[JsonPropertyName("EnableVideoStream")] public bool EnableVideoStream { get; set; } = false;
/// <summary>HD video (ddagrab GPU capture): cap width (0 = native window size — sharper; lower it,
/// e.g. 1280, to favour hitting 60fps on a slower CPU), nominal fps, and target bitrate (kbps).</summary>
[JsonPropertyName("VideoMaxWidth")] public int VideoMaxWidth { get; set; } = 0; // 0 = native (VideoToolbox has no level cap)
[JsonPropertyName("VideoFps")] public int VideoFps { get; set; } = 60;
[JsonPropertyName("VideoBitrateKbps")] public int VideoBitrateKbps { get; set; } = 12000;
/// <summary>portal.dat used to decode item icons for GET /icon (read-only inventory viewer). Defaults to
/// the RynthCore client's private copy. If the file is absent (e.g. an agent running off the game box)
/// /icon 404s and the app falls back to text rows — no other feature is affected.</summary>
[JsonPropertyName("IconDatPath")] public string IconDatPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "AcClient", "client_portal.dat");
/// <summary>Directory of RynthAi's baked dungeon floor-plan maps ({landblock:X8}_{layer}.bin), served as
/// PNGs via GET /map for the app's dungeon-map viewer. If the folder is absent (agent off the game box)
/// /maps returns an empty list and /map 404s — no other feature is affected.</summary>
[JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Maps");
/// <summary>cell.dat the landscape map (GET /worldmap) is drawn from, once, then cached as worldmap-v1.jpg in
/// <see cref="StatusDirectory"/>. Absent = no world map (capabilities.worldMap false); nothing else changes.</summary>
[JsonPropertyName("CellDatPath")] public string CellDatPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "AcClient", "client_cell_1.dat");
/// <summary>RynthNav's Atlas (NavData\locations.json), searched by GET /nav/search for the phone's Travel tab.
/// Absent = no travel (capabilities.travel false). The travel itself also needs EnableRemoteControl.</summary>
[JsonPropertyName("NavAtlasPath")] public string NavAtlasPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "NavData", "locations.json");
public static string DefaultConfigPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore", "statusagent.json");
// Indented, trim-safe context just for writing the human-edited template.
private static readonly AgentJsonContext IndentedContext =
new(new JsonSerializerOptions { WriteIndented = true });
/// <summary>
/// Load config from <paramref name="path"/>, creating a default template if
/// it doesn't exist. <paramref name="created"/> is set true when a fresh
/// template was written, so the caller can tell the user where it lives.
/// </summary>
public static AgentConfig LoadOrCreate(string path, out bool created)
{
created = false;
try
{
if (File.Exists(path))
{
string json = File.ReadAllText(path);
AgentConfig? cfg = JsonSerializer.Deserialize(json, AgentJsonContext.Default.AgentConfig);
if (cfg != null) return cfg;
}
}
catch (Exception ex)
{
AgentLog.Warn($"Failed to read config '{path}' ({ex.Message}); using defaults.");
return new AgentConfig();
}
var fresh = new AgentConfig();
try
{
string? dir = Path.GetDirectoryName(path);
if (dir != null) Directory.CreateDirectory(dir);
File.WriteAllText(path, JsonSerializer.Serialize(fresh, IndentedContext.AgentConfig));
created = true;
}
catch (Exception ex)
{
AgentLog.Warn($"Could not write template config '{path}' ({ex.Message}).");
}
return fresh;
}
public string EffectiveHost =>
string.IsNullOrWhiteSpace(Host) ? SafeMachineName() : Host;
private static string SafeMachineName()
{
try { return Environment.MachineName; }
catch { return "unknown"; }
}
}