using System.Text.Json; using System.Text.Json.Serialization; using RynthCore.Install; namespace RynthCore.StatusAgent; /// /// Agent configuration, loaded from %APPDATA%\RynthCore\statusagent.json. /// The agent writes a commented template here on first run and never sends /// anything until is set to a non-empty URL. /// internal sealed class AgentConfig { /// Backend URL the agent POSTs the status payload to. EMPTY = the /// agent never opens a network connection (local print-only mode). [JsonPropertyName("Endpoint")] public string Endpoint { get; set; } = ""; /// Optional auth header sent with each POST (e.g. "Authorization"). [JsonPropertyName("AuthHeaderName")] public string AuthHeaderName { get; set; } = "Authorization"; /// Value for (e.g. "Bearer <token>"). Empty = no header. [JsonPropertyName("AuthHeaderValue")] public string AuthHeaderValue { get; set; } = ""; /// Seconds between status posts. [JsonPropertyName("IntervalSeconds")] public int IntervalSeconds { get; set; } = 5; /// HTTP request timeout in seconds. [JsonPropertyName("TimeoutSeconds")] public int TimeoutSeconds { get; set; } = 15; /// Directory holding the engine's per-client status files. [JsonPropertyName("StatusDirectory")] public string StatusDirectory { get; set; } = Path.Combine(RynthInstallPaths.CoreLogsDir, "status"); /// Directory holding per-client RynthCore.<pid>.log files (heartbeat fallback). [JsonPropertyName("LogDirectory")] public string LogDirectory { get; set; } = RynthInstallPaths.CoreLogsDir; /// 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). [JsonPropertyName("UseHeartbeatLogFallback")] public bool UseHeartbeatLogFallback { get; set; } = true; /// A live-PID client whose snapshot is older than this is reported "hung". [JsonPropertyName("StaleAfterSeconds")] public int StaleAfterSeconds { get; set; } = 12; /// A dead-PID status file older than this is reported once then deleted. [JsonPropertyName("DropDeadAfterSeconds")] public int DropDeadAfterSeconds { get; set; } = 300; /// Label for this machine in the payload. Empty = use the machine name. [JsonPropertyName("Host")] public string Host { get; set; } = ""; // ── Pull delivery: let an app fetch status instead of (or as well as) POST ── /// When true, the agent serves the latest status at GET /status on /// so an app can pull it with no backend. Default /// false — no socket is opened unless you turn this on. [JsonPropertyName("ServeHttp")] public bool ServeHttp { get; set; } = false; /// 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 '/'. [JsonPropertyName("ServePrefix")] public string ServePrefix { get; set; } = "http://127.0.0.1:8740/"; /// Shared secret, required when is on: every route but /// /healthz needs Authorization: Bearer <token> or ?token=. Empty = /// the server stays off, on any bind (it can stream the screens and click in them). [JsonPropertyName("ServeToken")] public string ServeToken { get; set; } = ""; /// When true, also write the latest rollup to /// Logs\status\aggregate.json — handy for file-sync delivery or debugging. [JsonPropertyName("WriteAggregateFile")] public bool WriteAggregateFile { get; set; } = true; /// When true, the agent accepts POST /command 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 like GET. /// Commands are written under \commands. [JsonPropertyName("EnableRemoteControl")] public bool EnableRemoteControl { get; set; } = false; /// When true, the agent serves a live screen capture of an AC client window: /// GET /stream?pid=N (MJPEG) and GET /frame?pid=N (single JPEG). Captures the /// window's on-screen rectangle ONLY while a client is connected — no cost otherwise. Default /// FALSE. Honours . Only captures windows that are actually rendering /// (visible/restored — a minimized client has no frame). [JsonPropertyName("EnableScreenStream")] public bool EnableScreenStream { get; set; } = false; /// JPEG quality (1–100) and target frame interval (ms) for the screen stream. [JsonPropertyName("StreamQuality")] public int StreamQuality { get; set; } = 55; [JsonPropertyName("StreamIntervalMs")] public int StreamIntervalMs { get; set; } = 400; /// 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. [JsonPropertyName("EnableVideoStream")] public bool EnableVideoStream { get; set; } = false; /// 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). [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; /// 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. [JsonPropertyName("IconDatPath")] public string IconDatPath { get; set; } = Path.Combine(RynthInstallPaths.CoreDir, "AcClient", "client_portal.dat"); /// 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. [JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = Path.Combine(RynthInstallPaths.RynthAiDir, "Maps"); 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 }); /// /// Load config from , creating a default template if /// it doesn't exist. is set true when a fresh /// template was written, so the caller can tell the user where it lives. /// 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"; } } }