diff --git a/AGENTS.md b/AGENTS.md index 3a41fe9..d3b25d0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,7 @@ - This repository contains independent BepInEx 5.x C# mods for Dyson Sphere Program. HarmonyLib patches game methods at runtime; `UXAssist` is the shared library used directly by `CheatEnabler` and `UniverseGenTweaks`. - Projects target `net472` or `netstandard2.1` with SDK-style `.csproj` files. Compile-time game references live in `AssemblyFromGame/`. - `DustbinPreloader` and `LabOptPreloader` are Mono.Cecil preloaders; their main mods consume the injected fields without reflection. +- LiveStreamAssist: [project design and implementation plan](LiveStreamAssist/docs/WebSocketDesign.md). ## Build diff --git a/LiveStreamAssist/README.md b/LiveStreamAssist/README.md index f4e81c6..5f3b968 100644 --- a/LiveStreamAssist/README.md +++ b/LiveStreamAssist/README.md @@ -10,3 +10,10 @@ Keeps the Dyson Sphere Program statistics window active during a live stream by - Closing the statistics window stops the assist automatically. The mod requires UXAssist. + +## Developer documentation + +The WebSocket API is planned and is not implemented yet. + +- [WebSocket API reference](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketApi.md) +- [WebSocket design and implementation plan](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketDesign.md) diff --git a/LiveStreamAssist/docs/WebSocketApi.md b/LiveStreamAssist/docs/WebSocketApi.md new file mode 100644 index 0000000..eb6f640 --- /dev/null +++ b/LiveStreamAssist/docs/WebSocketApi.md @@ -0,0 +1,495 @@ +# LiveStreamAssist WebSocket API + +Status: planned contract for API `1.0.0`; the WebSocket service is not implemented yet. This reference describes the intended first release, not functionality available in the current mod. + +Audience: developers of live-stream overlays, OBS integrations, and other clients. Server architecture and implementation tasks are documented separately in the [design and implementation plan](WebSocketDesign.md). + +## Connection + +```text +ws://:18080/api/v1 +``` + +The service supports local and LAN clients without authentication. No token, login request, or application-level handshake is required. The client sends requests after the WebSocket connection opens. Other URL paths are rejected and must not execute API requests. + +The planned BepInEx configuration section is `WebSocketApi`: + +| Setting | Type | Default | Meaning | +| --- | --- | --- | --- | +| `Enabled` | Boolean | `false` | Start the listener when the mod starts. | +| `ListenAddress` | IP address string | `127.0.0.1` | Bind address; use a specific LAN address or `0.0.0.0` for LAN access. | +| `Port` | Integer, 1 through 65535 | `18080` | Listening port. | + +Configuration changes require a game restart in v1. The server remains available when leaving a save. Reflection reads require an active player game; menu-demo data is not exposed as a player game. + +Suggested client sequence: + +1. Call `system.info` to read versions, capabilities, and limits. +2. Optionally call `system.validate` to check the client's requirements. +3. Call `data.roots`, then use `data.describe` to discover readable members. +4. Call `data.read` and schedule any subsequent polling in the client. + +There are no subscriptions or unsolicited application messages. Normal WebSocket control frames, including ping/pong and close frames, are transport operations rather than application notifications. + +## Message format + +The API uses a restricted JSON-RPC 2.0 request/response format. It does not implement the full JSON-RPC feature set: batches and notification requests are deliberately rejected. + +Each complete WebSocket text message contains one UTF-8 JSON object. Fragmentation is supported at the WebSocket transport layer; an individual frame is not necessarily a complete JSON message. + +### Request + +```json +{ + "jsonrpc": "2.0", + "id": "request-1", + "method": "system.ping", + "params": {} +} +``` + +| Field | Required | Rules | +| --- | --- | --- | +| `jsonrpc` | Yes | Exactly `"2.0"`. | +| `id` | Yes | Nonempty string, at most 64 UTF-16 code units. Unique among outstanding requests on this connection. | +| `method` | Yes | Case-sensitive method name from this reference. | +| `params` | No | An object; omission is equivalent to `{}`. Positional parameter arrays are unsupported. | + +Identifiers, root names, member names, and capability names use ordinal, case-sensitive comparison. Unknown method parameters are rejected rather than silently ignored. Duplicate JSON object property names are rejected with `PARSE_ERROR` and `id: null`. Clients must ignore additional response fields introduced by compatible API extensions. + +Missing, null, numeric, or otherwise invalid IDs produce an invalid-request response with `id: null`. A message without an ID is not treated as a notification. A batch array produces one invalid-request response with `id: null`. + +Reusing an outstanding ID closes the connection with code `1008` and cancels its outstanding requests, avoiding ambiguous responses. An ID may be reused after its previous response has completed, although monotonically increasing client IDs are simpler. + +### Response + +```json +{ + "jsonrpc": "2.0", + "id": "request-1", + "result": { + "serverTimeUtc": "2026-09-17T12:00:00.0000000Z" + } +} +``` + +A response contains exactly one of `result` or `error`. Responses may arrive out of request order; correlate them by `id`. An accepted request completes at most once. Disconnection or server shutdown can prevent delivery; the server does not replay requests after reconnection. + +All timestamps and game values in examples are illustrative. + +## Versions and capabilities + +The following versions have different meanings: + +| Field | Meaning | +| --- | --- | +| `jsonrpc` | Envelope format version, always `"2.0"`. | +| `apiVersion` | API semantic version, initially `"1.0.0"`. The URL selects its major version. | +| `modVersion` | Installed LiveStreamAssist plugin version. | +| `gameVersion` | Running DSP version string, without the separate build number. | +| `gameBuild` | Running DSP build number, as an integer. | + +Breaking API changes require a new API major version. Compatible additions use a minor version; compatible fixes use a patch version. Raw game member names and types can change when DSP changes even if the API version does not. Discover members for the running game rather than assuming API compatibility also guarantees a particular reflection path. + +The first release advertises these capability keys: + +| Capability | Value | Meaning | +| --- | --- | --- | +| `reflection.read` | `true` | `data.read` is implemented. | +| `reflection.describe` | `true` | Root and member discovery are implemented. | +| `api.stats` | `false` | API statistics are reserved but not collected or returned. | +| `subscriptions` | `false` | Subscription and notification delivery are unsupported. | + +Unknown capabilities are unavailable. A development build must not advertise a capability before it actually implements it. + +## Limits + +These are the initial v1 defaults. `system.info.limits` is the authoritative source for the connected server. Byte limits count UTF-8 payload bytes, excluding WebSocket framing. A KiB is 1024 bytes. + +| `limits` field | Value | Meaning | +| --- | --- | --- | +| `maxConnections` | 8 | Simultaneous connections. | +| `maxPendingRequestsPerConnection` | 8 | Outstanding accepted requests on one connection. | +| `maxPendingRequests` | 64 | Outstanding accepted requests across the server. | +| `maxRequestBytes` | 65536 | Complete incoming message, including all fragments. | +| `maxResponseBytes` | 262144 | Complete outgoing JSON response. | +| `maxJsonDepth` | 32 | Maximum nesting of objects and arrays in a request. | +| `maxIdLength` | 64 | Request ID length in UTF-16 code units. | +| `maxPathSegments` | 16 | Segments in a reflection path. | +| `maxSelectMembers` | 32 | Members in an explicit projection. | +| `defaultPageSize` | 64 | Array/list page size when `limit` is omitted. | +| `maxPageSize` | 128 | Maximum requested array/list page size. | +| `requestTimeoutMs` | 5000 | Deadline for producing a response, measured from request admission. | +| `maxRequestsPerFrame` | 8 | Maximum game-data requests started in one Unity frame. | +| `mainThreadBudgetMs` | 2 | Soft main-thread scheduling budget per Unity frame. | + +Outstanding requests include queued reads, executing reads, and responses waiting to be sent. System methods also consume outstanding-request capacity, but do not consume the game-data execution budget. A saturated server returns `SERVER_BUSY` when it can deliver an error without growing the send queue; otherwise it closes the connection with `1013`. + +The main-thread budget does not preempt a running read. Deadlines are independent of game ticks and pause state. A timed-out request cannot later produce a success response. If a response cannot be delivered to a stalled client within the bounded send deadline, the connection closes instead of retaining output indefinitely. + +An oversized incoming message closes the connection with `1009`. A result that would exceed the response limit returns `LIMIT_EXCEEDED`; it is not silently truncated. + +## Methods + +### `system.ping` + +Parameters: none. + +Result: `{ "serverTimeUtc": "" }`. + +Tests application-level connectivity. It does not read game objects or wait for a game frame, so it can succeed while a game-data request times out during loading. UTC timestamps use ISO 8601 round-trip formatting with a `Z` suffix. + +### `system.info` + +Parameters: none. + +Returns versions, capabilities, and the limits listed above. It is available without an open save. + +```json +{ + "jsonrpc": "2.0", + "id": "info-1", + "result": { + "apiVersion": "1.0.0", + "modVersion": "1.0.0", + "gameVersionReady": false, + "gameVersion": null, + "gameBuild": null, + "capabilities": { + "reflection.read": true, + "reflection.describe": true, + "api.stats": false, + "subscriptions": false + }, + "limits": { + "maxConnections": 8, + "maxPendingRequestsPerConnection": 8, + "maxPendingRequests": 64, + "maxRequestBytes": 65536, + "maxResponseBytes": 262144, + "maxJsonDepth": 32, + "maxIdLength": 64, + "maxPathSegments": 16, + "maxSelectMembers": 32, + "defaultPageSize": 64, + "maxPageSize": 128, + "requestTimeoutMs": 5000, + "maxRequestsPerFrame": 8, + "mainThreadBudgetMs": 2 + } + } +} +``` + +Before game initialization supplies version information, `gameVersionReady` is `false` and both game version fields are `null`. Once ready, `gameVersionReady` is `true`, `gameVersion` is a string, and `gameBuild` is an integer. Leaving a save does not clear this process-level version information. + +### `system.validate` + +| Parameter | Required | Default | Rules | +| --- | --- | --- | --- | +| `apiMajor` | Yes | None | Positive 32-bit integer. | +| `requiredCapabilities` | No | `[]` | At most 32 distinct, nonempty capability-name strings. | + +```json +{ + "jsonrpc": "2.0", + "id": "validate-1", + "method": "system.validate", + "params": { + "apiMajor": 1, + "requiredCapabilities": ["reflection.read", "api.stats"] + } +} +``` + +```json +{ + "jsonrpc": "2.0", + "id": "validate-1", + "result": { + "compatible": false, + "apiVersion": "1.0.0", + "apiMajorCompatible": true, + "missingCapabilities": ["api.stats"] + } +} +``` + +`compatible` is true only when the requested API major matches and every required capability is true. `missingCapabilities` preserves request order and includes unknown capability names. A major mismatch or unavailable capability is a successful validation result with `compatible: false`, not a protocol error. + +This is not authentication, game-version certification, or reflection-path validation. Calling it does not negotiate connection state or gate later requests. + +### `system.stats` + +Parameters: none. + +The v1 result is exactly: + +```json +{ + "available": false, + "metrics": null +} +``` + +The method exists as a placeholder even though `api.stats` is false. It must not return fabricated zero counters. Future metrics will be specified separately before this capability becomes true. + +### `data.roots` + +Parameters: none. + +Returns `gameReady`, `sessionId`, `gameTick`, and a `roots` array. Each root entry has `name`, `type`, and `available` fields. All root names are always listed. + +| Root | Declared type | Meaning | +| --- | --- | --- | +| `game` | `GameData` | Active player-game data. | +| `player` | `Player` | Main player. | +| `history` | `GameHistoryData` | Research and progression data. | +| `statistics` | `GameStatData` | In-game statistics data, unrelated to `system.stats`. | +| `galaxy` | `GalaxyData` | Current galaxy. | +| `localPlanet` | `PlanetData` | Current local planet, if present. | +| `localStar` | `StarData` | Current local star, if present. | + +Without an active player game, `gameReady` is false, `sessionId` and `gameTick` are null, and every root is unavailable. A paused player game is ready. A local planet or star can be unavailable during space travel even while `gameReady` is true. + +`sessionId` is an opaque identifier for one loaded/new game session. It changes when a different session starts, including reloading the same save. `gameTick` is a decimal string. Discovery requires a main-thread turn and can time out if the game loop is blocked. + +### Reflection paths + +`data.describe` and `data.read` share these parameters: + +| Parameter | Required | Default | Rules | +| --- | --- | --- | --- | +| `root` | Yes | None | One registered root name. Arbitrary CLR type names are not roots. | +| `path` | No | `[]` | At most 16 path segments; an empty path addresses the root itself. | + +| Segment | Meaning | Example | +| --- | --- | --- | +| Nonempty string | Exact instance field or permitted property name. | `"currentTech"` | +| Nonnegative 32-bit integer | Zero-based array/list index. | `0` | +| Object containing only `key` | Exact dictionary-key lookup. | `{"key": 1001}` | + +Strings are literal member names, not expressions: `"history.currentTech"` is not split at the dot. Wildcards, method calls, filters, arithmetic, and arbitrary indexer invocation are unsupported. + +V1 supports one-dimensional zero-based arrays, concrete BCL `List`, and concrete BCL `Dictionary` with `Int32` or string keys. String keys are not converted to integers. Other collection implementations and arbitrary `IEnumerable` enumeration are unsupported. + +Fields can be public or non-public instance fields on permitted game-data types. Static fields, compiler-generated backing fields, methods, setters, and indexer properties are not exposed. Property reads require an explicit server allowlist. The initial property allowlist contains `GameHistoryData.currentTech`; other getters are not automatically allowed merely because they are public or have no setter. + +Use `data.describe` to discover the permitted surface. If inheritance hides a name, the most-derived declaration wins. Field/property traversal through runtime infrastructure such as Unity native objects, delegates, reflection objects, streams, or synchronization objects is unsupported. + +Reflected values use DSP's native units and member names. The API does not localize member names, convert values to UI display units, or calculate aggregate gameplay statistics. + +### `data.describe` + +Parameters: `root` and optional `path` only. + +Returns metadata for the addressed value: + +| Result field | Meaning | +| --- | --- | +| `type` | Diagnostic CLR type name; runtime type when non-null, declared type when null. | +| `isNull` | Whether the addressed value is null. | +| `members` | Permitted members, sorted by ordinal name. Each has `name`, `type`, and `kind` (`field` or `property`). | +| `collection` | Null for non-collections; otherwise `kind` (`array`, `list`, or `dictionary`), `elementType`, `keyType`, and `count`. | +| `sessionId` | Session that supplied the metadata. | +| `gameTick` | Sampling tick as a decimal string. | + +For arrays/lists, `keyType` is null. For a null collection, `count` is null. Scalars and supported BCL containers have an empty `members` array; their framework internals are not exposed. A null terminal value can still be described using its declared type. + +Resolving the explicit path can read permitted getters. Listing the target's members does not evaluate those members, their getters, or collection elements. Denied members are omitted. Type names are diagnostic metadata, not instructions to load CLR types in a client. + +This method requires an active game and an available root. Passing through null before the final segment fails with `NULL_PATH`. + +### `data.read` + +Additional parameters: + +| Parameter | Required | Default | Rules | +| --- | --- | --- | --- | +| `select` | No | Omitted | 1 through 32 distinct, nonempty immediate member names for an object projection or for each object in an array/list page. No nested selection syntax. | +| `offset` | No | `0` | Nonnegative 32-bit integer; valid only when the terminal value is an array/list. | +| `limit` | No | `64` | Integer from 1 through 128; valid only when the terminal value is an array/list. | + +The result always contains `type`, `value`, `sessionId`, and `gameTick`. `type` follows the same rule as in `data.describe`. A read or projection fails as a whole if any requested member cannot be read; v1 has no partial-success envelope. + +Terminal-value behavior: + +| Terminal value | `value` representation | +| --- | --- | +| Null | JSON null; no further member/element reads occur. | +| Scalar | Encoded scalar, as specified below. | +| Object without `select` | A shallow object summary. | +| Object with `select` | An object containing exactly the selected members. | +| Array/list | A page object containing `items`, `offset`, `totalCount`, and `hasMore`. | +| Supported dictionary | A shallow dictionary summary; read individual entries using a key path segment. | + +`select` is invalid for non-null scalar and dictionary terminals. In a collection page it applies to each non-null object element; requesting it for scalar elements is invalid. Null elements remain null. `offset` or `limit` on a non-collection is invalid, including null values whose declared type is not an array/list. Parameters are validated even when the selected page is empty; member availability is checked on objects actually read. + +Pages return up to `limit` items. `offset` at or beyond the current count returns an empty page, preserving the requested offset, with `hasMore: false`. A single-element path index at or beyond the count is instead `INDEX_OUT_OF_RANGE`. `totalCount` means the underlying container count, not the number of live entities in a DSP pool. No filtering, compaction, sorting, or zero-ID skipping is implied. Pages from different requests need not describe an unchanged collection. + +Complex values inside a projection or page remain summaries unless they are the direct objects selected by the request. The server never recursively expands an entire object graph. Summary shapes are: + +```json +{ + "$kind": "object", + "$type": "GameData" +} +``` + +```json +{ + "$kind": "array", + "$type": "System.Int32[]", + "count": 8 +} +``` + +Collection summaries use `$kind` values `array`, `list`, or `dictionary` and include `count`. The dollar-prefixed keys belong to the wire representation, not to the reflected object's members. To expand a summarized value, issue another request whose path addresses that value. + +Scalar encoding: + +| CLR value | JSON encoding | +| --- | --- | +| Boolean, string | Boolean or string. | +| Character | One-character string. | +| Signed/unsigned integers up to 32 bits | Number. | +| `Int64`, `UInt64` | Invariant decimal string, even when the value would fit JavaScript's safe-integer range. | +| Finite `Single`, `Double` | Number. | +| `Decimal` | Invariant decimal string. | +| Enum | Object with `name` (declared name or null) and `value` (underlying integer as a decimal string). | +| `DateTime`, `DateTimeOffset` | ISO 8601 round-trip string; preserve the source time-zone/Kind information. An unspecified `DateTime` has no implied UTC suffix. | +| `Guid` | Standard hyphenated string. | + +Non-finite floating-point values fail with `UNSUPPORTED_VALUE`. Unsupported runtime types fail with `UNSUPPORTED_TYPE`; the server does not serialize their internals or call arbitrary `ToString()` implementations. Plain game-data structs, including position structs defined by DSP, follow the object/projection rules. Unity `Vector2`, `Vector3`, `Vector4`, and `Quaternion` support their instance fields through the same rules; Unity objects such as components and textures do not. + +#### Research read example + +First read `history` at `["currentTech"]`; a value of zero means there is no current research. Use a nonzero returned ID as the dictionary key, rather than assuming the illustrative ID below is active: + +```json +{ + "jsonrpc": "2.0", + "id": "research-1", + "method": "data.read", + "params": { + "root": "history", + "path": ["techStates", {"key": 1001}], + "select": ["curLevel", "hashUploaded", "hashNeeded"] + } +} +``` + +```json +{ + "jsonrpc": "2.0", + "id": "research-1", + "result": { + "type": "TechState", + "value": { + "curLevel": 3, + "hashUploaded": "12345678901234567", + "hashNeeded": "22345678901234567" + }, + "sessionId": "session-1", + "gameTick": "6000" + } +} +``` + +#### Array read example + +```json +{ + "jsonrpc": "2.0", + "id": "queue-1", + "method": "data.read", + "params": { + "root": "history", + "path": ["techQueue"], + "offset": 0, + "limit": 2 + } +} +``` + +```json +{ + "jsonrpc": "2.0", + "id": "queue-1", + "result": { + "type": "System.Int32[]", + "value": { + "items": [1001, 1002], + "offset": 0, + "totalCount": 8, + "hasMore": true + }, + "sessionId": "session-1", + "gameTick": "6000" + } +} +``` + +## Game state and consistency + +- Menu demos, loading, and the absence of a running player game make `data.read` and `data.describe` fail with `GAME_NOT_READY`. `data.roots` can still report unavailability. +- An unavailable known root during an active game, such as `localPlanet` during space travel, produces `ROOT_UNAVAILABLE`. This differs from a null terminal member on an available root. +- Every game-data request is associated with the session state in which it was admitted. A queued request cannot silently read a subsequently loaded save; a session transition invalidates it with `SESSION_CHANGED`. +- Results are detached samples taken on the main thread. `gameTick` identifies sampling time; it is not a transactional snapshot ID. No cross-request or globally atomic game-world snapshot is promised. +- A response sampled before a session transition may already be in transit. Clients should use `sessionId` and new discovery results to discard data belonging to a previous session. + +## Errors and recovery + +```json +{ + "jsonrpc": "2.0", + "id": "read-1", + "error": { + "code": -32001, + "message": "Game data is unavailable.", + "data": { + "kind": "GAME_NOT_READY" + } + } +} +``` + +`message` is English diagnostic text, not a stable identifier. `error.data.kind` is stable. Error data may additionally contain `segmentIndex` (zero-based), `member`, or `root` to identify the failure. Stack traces, filesystem paths, and exception objects are not returned. + +| Code | Kind | Meaning / client action | +| --- | --- | --- | +| `-32700` | `PARSE_ERROR` | Malformed JSON or duplicate object keys; response ID is null. Correct the message. | +| `-32600` | `INVALID_REQUEST` | Invalid envelope, batch, or invalid/missing ID. Correct the request; ID is null if it cannot be reliably determined. | +| `-32601` | `METHOD_NOT_FOUND` | Unknown method. Check API version and method spelling. | +| `-32602` | `INVALID_PARAMS` | Wrong/missing/unknown parameter or invalid parameter combination. Correct the request. | +| `-32603` | `INTERNAL_ERROR` | Unexpected server failure. Inspect server logs. | +| `-32001` | `GAME_NOT_READY` | No ready player game. Poll root availability before retrying. | +| `-32002` | `ROOT_NOT_FOUND` | Unknown root name. Rediscover roots. | +| `-32003` | `ROOT_UNAVAILABLE` | Known root is absent in this game state. Wait for it to become available. | +| `-32004` | `MEMBER_NOT_FOUND` | Requested member does not exist. Rediscover members for this game version. | +| `-32005` | `MEMBER_NOT_ALLOWED` | Member exists but is outside the read policy. Choose an exposed member. | +| `-32006` | `NULL_PATH` | Null encountered before completing the path. Query a shorter path or retry after state changes. | +| `-32007` | `INDEX_OUT_OF_RANGE` | Element index is outside the current array/list. Refresh collection metadata. | +| `-32008` | `KEY_NOT_FOUND` | Dictionary has no matching key. Refresh the source of the key. | +| `-32009` | `UNSUPPORTED_TYPE` | Value type or traversal operation is unsupported. Use supported data members. | +| `-32010` | `READ_FAILED` | A permitted read failed, including a getter exception. Inspect logs or rediscover the path. | +| `-32011` | `LIMIT_EXCEEDED` | A documented resource limit would be exceeded. Reduce depth, projection, page size, or output size. | +| `-32012` | `SERVER_BUSY` | Admission capacity is exhausted. Reduce concurrent requests and back off. | +| `-32013` | `REQUEST_TIMEOUT` | Response production exceeded its deadline. Retry later with a new ID. | +| `-32014` | `SESSION_CHANGED` | Session changed after admission. Rediscover roots and discard old-session work. | +| `-32015` | `UNSUPPORTED_VALUE` | Value cannot be represented under the scalar rules. | + +Malformed parameter types and negative indexes/offsets are `INVALID_PARAMS`. For otherwise well-formed method parameters, exceeding a documented positive maximum, such as path length or page size, is `LIMIT_EXCEEDED`. Envelope validity and transport limits follow their specific rules above. A well-formed but unknown root is `ROOT_NOT_FOUND` before game availability is evaluated. Path resolution then stops at its first failure. + +Transport closure codes relevant to clients: + +| Code | Meaning | +| --- | --- | +| `1001` | Server is stopping. | +| `1003` | Binary application message is unsupported. | +| `1007` | Invalid UTF-8 payload. | +| `1008` | Protocol violation such as reuse of an outstanding ID. | +| `1009` | Incoming message is too large. | +| `1013` | Overload or inability to drain a bounded send queue. | + +Do not retry invalid paths unchanged in a tight loop. Game-state errors can be retried after discovery; overload and timeouts require client-side backoff. Reconnection creates a new request-ID namespace but does not restore any requests from the old connection. diff --git a/LiveStreamAssist/docs/WebSocketDesign.md b/LiveStreamAssist/docs/WebSocketDesign.md new file mode 100644 index 0000000..df91cf3 --- /dev/null +++ b/LiveStreamAssist/docs/WebSocketDesign.md @@ -0,0 +1,290 @@ +# LiveStreamAssist WebSocket Design and Implementation Plan + +Status: implementation not started. This document is the handoff for a later implementation session. The current mod only implements statistics-window tab switching. The next implementation task is **Phase 0: runtime transport verification**. + +The [API reference](WebSocketApi.md) defines the client-visible contract. This document defines the scope, implementation constraints, source references, work order, and acceptance checks. Keep API usage documentation separate from implementation investigation and progress notes. + +## Confirmed scope + +The following decisions were confirmed with the user and must survive a session handoff: + +- Support both local and LAN WebSocket clients. +- Use **no authentication** in v1. The user explicitly chose this after LAN access was discussed. Do not add a shared token, login endpoint, accounts, or permissions workflow. +- Provide read-only, client-initiated requests for in-game data, primarily through reflection. +- Provide connectivity and API-compatibility validation. Here, validation does not mean identity authentication or a separate reflection-path-validation API. +- Report the API version, mod version, running game version, and running game build. +- Reserve API statistics through `system.stats`, returning `available: false` and `metrics: null`; advertise `api.stats: false`. +- Do not implement subscriptions, application notifications, batch requests, game writes, arbitrary method invocation, or script evaluation. +- Preserve the existing Ctrl+F8 statistics-window feature and its independent state. + +Keep the implementation small: one listener, a fixed method switch, fixed root providers, a bounded main-thread dispatcher, and shallow result projection. No RPC framework, general-purpose reflection service, dependency-injection container, external server process, HTTP REST API, web dashboard, or custom WebSocket framing implementation is required. + +The initial listener configuration and all wire limits are defined in [API connection settings](WebSocketApi.md#connection) and [API limits](WebSocketApi.md#limits). Keep those tables as the single documentation source for their values. Configuration is startup-only in v1; do not introduce live configuration reload as part of this work. + +## Starting or resuming implementation + +1. Read the repository `AGENTS.md`, this document, and the API reference before editing code. +2. Inspect `git status` and the current diff. Treat existing changes as user work. Check whether some phases have already been implemented rather than assuming this document's initial status still describes the checkout. +3. Read the source entry points in the next section. Preserve the host-owned feature lifecycle and existing keyboard handling. +4. Recheck runtime-specific assumptions against the installed game's original assemblies if DSP or Unity has changed. Do not use stripped reference DLL method bodies as evidence. +5. Complete phases in dependency order. Mark a phase complete only after its acceptance checks pass; identify unavailable real-game or LAN checks as blocked, not passed. +6. If pausing between sessions, update this document's current status, remaining phase checks, selected dependency versions, and concrete blockers. Replace stale notes instead of appending a chronological transcript. Keep project-specific guidance here; `AGENTS.md` should contain only a link to this document. + +The API reference is the source of truth for method names, message shapes, numeric error codes, null behavior, and capability names. Resolve any conflict with this plan before implementing it. The transport package/version is intentionally provisional until Phase 0; that is not permission to redesign the protocol or expand the confirmed scope. + +## Repository entry points + +Paths in this table are relative to the repository root. + +| File / symbol | Why it matters | +| --- | --- | +| `LiveStreamAssist/LiveStreamAssist.cs` / `LiveStreamAssist.Awake` | BepInEx plugin startup; performs localization setup and feature discovery. Bind API configuration before discovery. | +| `LiveStreamAssist/LiveStreamAssist.cs` / `LiveStreamAssistFeature` | Existing feature, order 50; owns Ctrl+F8 and statistics-window switching. Its `_enabled` flag is not the server-enabled flag. | +| `LiveStreamAssist/LiveStreamAssist.csproj` | Inherits `net472`, currently references UXAssist, and owns the mod version. Add only the server's required dependencies and project-scoped packaging customization here. | +| `UXAssist/Common/ModFeatures/ModFeatureRegistry.cs` | Initializes discovered features eagerly. UXAssist alone drives `StartAll`, `UninitAll`, and update dispatchers. | +| `UXAssist/UXAssist.cs` / `Update` | Skips feature updates while `VFInput.inputing` or `DSPGame.IsMenuDemo` is true. This is unsuitable as the sole server request pump. | +| `UXAssist/Common/GameLogic.cs` | Supplies `OnDataLoaded`, `OnGameBegin`, and `OnGameEnd` callbacks. Use the fully qualified UXAssist type or the existing `GameLogicProc` alias to avoid DSP's own `GameLogic` type. | +| `Directory.Build.props` | Shared BepInEx dependencies, Unity compile assets, original-game reference refresh dependency, and warning policy. | +| `Directory.Build.targets` / `ZipMod` | Packages the main assembly and selected root files. It does not automatically package NuGet runtime dependencies. | +| `UpdateGameDlls.ps1` | Documents Steam registry and `libraryfolders.vdf` discovery. Running it updates/publicizes compile references; read it for installation discovery rather than using its outputs for decompilation. | +| `LuaScriptEngine/LuaState.cs` | Existing research/statistics access examples, not a reusable WebSocket server. LuaScriptEngine is not a dependency of this feature. | + +### Verified original-runtime facts + +These facts were checked while preparing the plan. They are implementation constraints, not a substitute for testing the selected library in DSP: + +| Original assembly / symbol | Finding and consequence | +| --- | --- | +| `System.dll` / `System.Net.HttpListenerContext.AcceptWebSocketAsync` | The inspected overloads throw `NotImplementedException`. Do not select the framework `HttpListener` WebSocket server path on the basis of desktop .NET tests. | +| `UnityEngine.CoreModule.dll` / `UnityEngine.UnitySynchronizationContext` | `Post` enqueues work; `Exec` copies queued work before running callbacks. Capture the installed main-thread context and post a bounded pump through it. | +| `Assembly-CSharp.dll` / `GameConfig` | Supplies `gameVersion` and the separate `build` field. Read these from the running game. | +| `Assembly-CSharp.dll` / global `Version` | DSP has its own `Version` struct. `ToString()` omits its `Build` field. Do not confuse this type with `System.Version` or assume an assembly version is the game version. | +| `Assembly-CSharp.dll` / `GameMain` | Root getters return current `GameData` members. Menu demos can have allocated game data; checking only `GameMain.data != null` is insufficient. Pausing does not end a running game. | +| `Assembly-CSharp.dll` / `VFPreload` | `InvokeOnLoadWorkEnded` runs before `done` becomes true. `done`/`dbDone` can be used to detect an already completed preload when starting late; do not require them to be true inside the load-work-ended callback itself. | +| `Assembly-CSharp.dll` / `GameHistoryData.currentTech` | This is an auto-property with a public getter and private setter, not a public field. The getter only returns its backing value and is the initial allowed property. | +| `Assembly-CSharp.dll` / `GameConfig` getters | Some apparently readable properties create directories. Public visibility or the absence of a public setter does not establish a side-effect-free getter. | + +To reproduce inspection, locate Steam using the registry and parse `steamapps/libraryfolders.vdf` for app ID `1366540`, as `UpdateGameDlls.ps1` does. Resolve `/DSPGAME_Data/Managed/` and decompile the installed original DLLs, for example: + +```text +ilspycmd --disable-updatecheck -t GameConfig /Assembly-CSharp.dll +ilspycmd --disable-updatecheck -t Version /Assembly-CSharp.dll +ilspycmd --disable-updatecheck -t GameMain /Assembly-CSharp.dll +ilspycmd --disable-updatecheck -t GameHistoryData /Assembly-CSharp.dll +ilspycmd --disable-updatecheck -t VFPreload /Assembly-CSharp.dll +ilspycmd --disable-updatecheck -t UnityEngine.UnitySynchronizationContext /UnityEngine.CoreModule.dll +ilspycmd --disable-updatecheck -t System.Net.HttpListenerContext /System.dll +``` + +Replace placeholders and quote paths containing spaces. Do not depend on this session's temporary decompilation output or a hard-coded Steam drive letter. Do not commit game DLLs or decompiled game source. + +## Intended code organization + +Use these responsibilities as the starting layout; keep small private helpers with their owner rather than creating an interface or service for each step. + +| Planned file | Responsibility | +| --- | --- | +| `LiveStreamAssist/Api/WebSocketApiFeature.cs` | Configuration references, feature lifecycle, version publication, game-session tracking, and root providers. Suggested feature order: 51. | +| `LiveStreamAssist/Api/WebSocketApiServer.cs` | Listener, connections, message admission, serialized sends, and connection cleanup. | +| `LiveStreamAssist/Api/ApiProtocol.cs` | DTOs, error constants, validation, fixed method dispatch, system methods, and the API version constant. | +| `LiveStreamAssist/Api/ReflectionReader.cs` | Shared path resolution, allowed-member discovery, value projection, and detached result construction. | +| `LiveStreamAssist/Api/MainThreadDispatcher.cs` | Bounded request queue, one scheduled pump, cancellation, and deadline/session checks. | +| `LiveStreamAssist/tools/Test-WebSocketApi.ps1` | Runnable WebSocket integration checks using PowerShell 7 and `System.Net.WebSockets.ClientWebSocket`. | + +Bind the three API settings in plugin startup before `ModFeatureRegistry.Discover`. Use a separate `[ModFeature]` class for the server. Do not have LiveStreamAssist call registry dispatchers, add a second shared update driver, relax UXAssist's menu/typing guards, or attach server activation to Ctrl+F8. + +Keep `net472`. Prefer one managed Mono-compatible WebSocket server dependency, initially evaluate Fleck, and explicitly reference Newtonsoft.Json. LuaScriptEngine's transitive Newtonsoft.Json reference does not make that DLL a guaranteed runtime dependency of LiveStreamAssist. Pin versions only after compatibility verification; record the chosen versions in this document and the project file. + +## Runtime design + +### Lifecycle and metadata + +- `Init`: prepare configuration references and non-network state. Keep initialization safe if the API is disabled. +- `Start`: if enabled, capture `SynchronizationContext.Current` on Unity's main thread, initialize a server owner instance, subscribe to game lifecycle events, and start the listener without blocking the game loop. If the current context is null or is not Unity's installed context, fail startup with a useful log; a newly constructed generic `SynchronizationContext` is not a main-thread dispatcher. +- Publish version data from `GameLogicProc.OnDataLoaded`. If starting after preload, use the original preload completion flags to populate it immediately. Publish an immutable snapshot; network callbacks never read `GameConfig` or Unity state directly. Preserve this snapshot across save changes. +- Source `modVersion` from generated `PluginInfo.PLUGIN_VERSION`. Keep `apiVersion` independent, initially `1.0.0`. Use the explicit `System.Version` name if parsing the API version to avoid DSP's global `Version` type. +- Subscribe to `OnGameBegin` and `OnGameEnd` for session transitions. Account for starting after a game has already begun. +- `Uninit`: stop admitting work, invalidate the owner/session, cancel requests, unsubscribe events, close the listener, and close connections. Clear metadata caches owned by the server. Posted callbacks must check their old owner token so they cannot run against a restarted instance. +- Startup errors, including an occupied port or invalid settings, disable only this server instance and are logged. Do not silently bind a different address/port or let an exception escape into other features' startup/shutdown. +- Start/stop and cleanup must be idempotent. Never synchronously wait on a task whose completion needs the Unity thread during shutdown. + +### Root providers and readiness + +Register these fixed mappings inside LiveStreamAssist: + +| Root | Provider | +| --- | --- | +| `game` | `GameMain.data` | +| `player` | `GameMain.mainPlayer` | +| `history` | `GameMain.history` | +| `statistics` | `GameMain.statistics` | +| `galaxy` | `GameMain.galaxy` | +| `localPlanet` | `GameMain.localPlanet` | +| `localStar` | `GameMain.localStar` | + +A player game is ready when `GameMain.data` exists, `GameMain.isRunning` is true, loading is false, and `DSPGame.IsMenuDemo` is false. Re-evaluate these conditions on the main thread at execution time. Do not reject an otherwise ready game because it is paused, a fullscreen UI is open, or text input is active. + +Root discovery always lists the fixed catalog, using declared types when no instance is available. `data.read`/`data.describe` reject a not-ready game. A known root that returns null during a ready game is `ROOT_UNAVAILABLE`; null reached at the end of a member path is a successful null value. + +Do not retain root instances, collection instances, or getter return objects in reflection caches. Resolve roots per request. Treat only the specified root set as remote entry points; exposing a client-supplied assembly/type name would bypass this boundary. + +### Network-to-main-thread flow + +```text +WebSocket callback + -> validate envelope, parameters, ID, size, and capacity + -> system method: respond from immutable/process-only data + -> game-data method: capture session generation and enqueue + -> one Unity SynchronizationContext.Post pump + -> recheck connection, deadline, session, and readiness + -> resolve root/path and build detached result + -> serialize and send off the Unity thread +``` + +- Network receive, JSON parsing, serialization, and socket sends stay off the Unity thread. Avoid accidentally capturing Unity's context in network async continuations. +- Only one pump callback may be scheduled per server owner at a time. Process work within the API's per-frame count and soft-time budget, then repost remaining work. Do not busy-wait, spin, or post one unbounded callback per request. Track the Unity frame for the budget if the context is pumped more than once in a frame. +- Use a standard queue with a small lock or `ConcurrentQueue` with correct admission accounting. A custom scheduler or lock-free queue is unnecessary. If using task completions, run continuations asynchronously so response work does not execute inline in the pump. +- A request owns one admission slot until response delivery or cancellation. Capacity includes outgoing responses. Serialize sends per connection, bound the send queue, and close slow consumers rather than retaining unlimited output. +- Expiry is based on monotonic elapsed time, not `Time.time` or game ticks. Check expiry before reading. Once timed out, work cannot later emit success. A deadline does not abort a getter halfway through; the read policy must keep getters short and bounded. +- Cancellation and session invalidation must remove or cheaply skip queued work and release its slot. Use one completion path so timeout, disconnect, and successful reads cannot double-complete or leak admission counts. +- The only mutable game references exist during main-thread execution. Return scalar values, strings, copied arrays/pages, and plain snapshot dictionaries/DTOs; never pass a live DSP object, boxed game struct with nested references, `MemberInfo`, or `UnityEngine.Object` to the background JSON serializer. + +### Session transitions + +Maintain an internal generation that changes at game-session boundaries and server stop, plus an opaque public `sessionId` for each ready player session. A GUID is sufficient for the public ID; it is not persisted and has no authentication meaning. + +Publish the current admission generation as immutable/thread-safe state. Each admitted game-data request records it without carrying a game object across threads. Before executing and before completing an in-progress sample, compare it with current state. Cancel pending old-generation work with `SESSION_CHANGED` instead of resolving its path against a new save. + +On game end, publish an unavailable session and invalidate pending work while keeping the listener and process-level version metadata alive. Game readiness checks still run when requests execute, covering state changes between callbacks. Already delivered/in-transit snapshots remain identified by their old `sessionId`; do not claim they can be recalled. + +### Reflection and serialization policy + +Use one resolver/member-policy path for `data.read`, `data.describe`, and projections. Fixing or restricting access must affect all three paths together. + +1. Validate segment kinds and bounds before invoking reflection. Retain whether `select`, `offset`, and `limit` were explicitly supplied; array/list defaults must not cause ordinary scalar reads to fail parameter validation. No dotted-path parser, expression compiler, wildcard search, or arbitrary indexer binder is needed. +2. Resolve instance fields with public and non-public visibility, walking declared members from the most-derived type toward base types. Skip static and compiler-generated fields. Apply type restrictions before traversing a value. A denied declaration does not fall back to a same-named base declaration. +3. Permit ordinary data types defined in the game's `Assembly-CSharp` assembly, the API's scalar types, the specified concrete BCL containers, and the listed Unity value structs. Apply infrastructure exclusions before the assembly allowance: being a game-defined subclass of `UnityEngine.Object`, a stream, or another runtime-service type does not make it readable. Do not traverse native handles, pointer/by-ref fields, delegates, `Type`/reflection metadata, tasks/threads, locks, streams, or arbitrary external-plugin types. +4. Generic getter access starts with this exact allowlist only: + + | Declaring type | Property | Verified behavior | + | --- | --- | --- | + | `GameHistoryData` | `currentTech` | Public auto-property getter returning its backing value; private setter is not exposed. | + + Additional properties require a concrete query need and inspection of the original getter and any called methods. Record the exact declaration and reason here and update the API reference before adding it. Do not allow every public getter, call a setter, or bypass a rejected getter through its compiler-generated backing field. + +5. Use concrete BCL array/list/dictionary adapters for indexing and counts. Do not accept arbitrary `IList`, `IDictionary`, or `IEnumerable` implementations merely because they expose a familiar interface. No full dictionary enumeration, custom collection internals, or pool compaction is needed in v1. +6. Keep projections shallow as specified by the API. Explicit paths may follow cyclic references within the path limit, but summaries terminate output traversal. No graph serializer, persistent object handles, reference registry, or general cycle-resolution framework is needed. +7. Encode 64-bit values and other scalars before passing snapshots to JSON serialization. Use Newtonsoft.Json without automatic CLR type construction (`TypeNameHandling.None`); parse request DTO/token data only. Never use `SerializeObject` or `JToken.FromObject` on an arbitrary game object. +8. Bound serialized output while producing it, not after creating an unlimited JSON string. Bound snapshot construction too: enforce projection/page limits and reject obviously oversized strings before copying/encoding them. Metadata discovery is shallow and must not execute listed getters. +9. Cache successful type/member metadata, not requests or failed arbitrary path strings. Use a bounded cache (for example, at most 1024 entries, then stop adding entries) rather than a new eviction framework. Clear it on server uninitialization. + +Catch reflection/getter failures at the request boundary and map them to the API errors. Retain diagnostic exceptions in local logs, not response bodies. System methods and generic game-data methods must share envelope/error handling; do not introduce parallel protocol implementations. + +## Implementation phases + +### Phase 0: runtime transport verification + +- [ ] Inspect the current project state and original runtime assumptions listed above. +- [ ] Evaluate Fleck first as a single managed WebSocket server dependency, plus an explicit Newtonsoft.Json dependency, while retaining `net472`. +- [ ] Verify the server inside actual DSP/BepInEx/Mono using a standard WebSocket client. A standalone .NET console server is not evidence of game-runtime compatibility. +- [ ] Verify text-message fragmentation, invalid UTF-8 handling, binary rejection, connection closure, and request-size enforcement before unbounded message accumulation. Check the library's behavior before promising a limit that its callbacks cannot enforce. +- [ ] Verify path rejection, clean listener disposal, occupied-port failure, and a bounded serialized send path. +- [ ] Record the selected package versions and any necessary runtime dependency DLLs here; pin them in `LiveStreamAssist.csproj`. + +If Fleck cannot meet the runtime or bounded-buffer requirements, evaluate one other small managed Mono-compatible server library and document the reason. Do not write a new framing stack, switch to an ASP.NET host, change the target framework, or add multiple competing transports to hide an unresolved compatibility problem. Treat missing real-game verification as a blocker. + +Exit condition: the selected transport can actually listen, exchange bounded messages, and release its resources in the game's runtime. Reuse the verified code in the implementation rather than leaving a second prototype server in the tree. + +### Phase 1: lifecycle, protocol, and system methods + +- [ ] Add the separate API feature and startup-only configuration; preserve the existing feature's registration and state. +- [ ] Implement request validation, ID tracking, fixed dispatch, response/error envelopes, capacity accounting, and serial sends. +- [ ] Implement `system.ping`, `system.info`, and `system.validate` with the specified state-independent semantics. +- [ ] Implement only the `system.stats` placeholder. Keep `api.stats` and `subscriptions` false; advertise reflection capabilities only when their implementations are ready. +- [ ] Publish runtime version metadata through main-thread initialization/lifecycle code and handle late feature startup. +- [ ] Add the integration script's no-save mode for system methods, malformed messages, invalid IDs, unknown methods, incompatible majors/capabilities, and the statistics placeholder. + +Exit condition: system methods work from local and LAN clients without authentication, including at the main menu. Version fields match the running game after preload. Startup/stop failures do not interrupt other features. Invalid requests produce the documented response or transport closure. + +### Phase 2: main-thread queries and reflection + +- [ ] Add the bounded synchronization-context pump and current-session admission state. +- [ ] Add the seven fixed root providers and readiness checks, including the menu-demo exclusion and paused-game allowance. +- [ ] Implement the shared member policy, exact getter allowlist, typed path traversal, null handling, and deterministic metadata listing. +- [ ] Implement scalar encoding, summaries, explicit projections, and array/list pages exactly as the API reference specifies. +- [ ] Attach `sessionId` and `gameTick` to game-data results; ensure returned snapshots contain no live game references. +- [ ] Extend the integration script with `-RequireGame` checks that discover roots, read `history.currentTech`, read `history.techQueue`, and inspect/read a research state using an ID obtained from the game. +- [ ] Leave one small runnable set of fixture-based checks for the production reflection/projection code, covering inherited private fields, blocked getters, null intermediates/terminals, dictionary key types, indexes, shallow cyclic references, 64-bit precision, and non-finite values. + +Keep fixture checks outside the shipped plugin and out of the remote root catalog. Use the smallest repository-compatible harness; no new testing framework or abstraction is required solely for these checks. Exercise the production reader, not a reimplementation of it, and record the exact run command here once its layout is chosen. + +Exit condition: returned research values match the in-game data, precision is preserved beyond `2^53`, rejected members cannot be reached through alternate read/describe/projection paths, and queries execute on Unity's main thread while typing or paused. + +### Phase 3: lifecycle races, resource bounds, and recovery + +- [ ] Verify a queued read cannot run against a different save after loading, unloading, or reloading a session. +- [ ] Verify timeout/disconnect/session-change races release admission capacity once and cannot emit late or duplicate success responses. +- [ ] Verify menu, loading, pause, space-travel root absence, and game-end behavior match the documented error distinctions. +- [ ] Exercise capacity and payload limits with multiple clients, fragmented oversized input, slow readers, and large projections/pages. Output must stay bounded during serialization, not merely fail after allocation. +- [ ] Verify an ordinary query still succeeds after malformed requests, busy responses, and other recoverable errors. +- [ ] Verify idempotent stop, released listener ports, ignored callbacks after disposal, and fail-soft behavior when another process owns the configured port. +- [ ] Regress Ctrl+F8 startup/stop, window closure, and the existing randomized tab switching. + +Exit condition: the server remains usable after recoverable failures, old sessions cannot leak through queued work, and overload cannot create unbounded queues or main-thread network work. Report actual observations rather than asserting an unmeasured FPS or latency guarantee. + +### Phase 4: packaging and final handoff + +- [ ] Add the selected runtime dependencies to LiveStreamAssist's package, scoped to this project. +- [ ] Build, run the fixture checks and integration script, and complete the manual real-game/LAN acceptance matrix below. +- [ ] Inspect the resulting ZIP and test a clean install with only the manifest-declared dependencies and packaged runtime DLLs. Do not rely on DLLs provided incidentally by LuaScriptEngine or the development environment. +- [ ] Update the API reference and project README to describe verified implemented behavior. Remove the planned-only status only when the implementation is actually ready. +- [ ] Update this design document's current status, dependency selection, verified environment, and any remaining blockers. Keep `AGENTS.md` as a documentation pointer instead of copying this plan into it. +- [ ] Run `git diff --check` and review the final diff for unrelated changes. + +The existing `ZipMod` target does not gather dependency DLLs automatically. Prefer a project-local target with `BeforeTargets="ZipMod"` that adds the explicitly selected runtime DLLs to `_PackRootFiles`; the shared target will then stage them along with the plugin. Confirm the ordering and actual resolved filenames in the build output. Do not copy the entire output directory: that can include game references, Unity assemblies, BepInEx assemblies, and UXAssist itself. No shared packaging redesign is needed. + +The project README can link to source-hosted developer documentation so its links also work when the README is distributed without the repository's `docs` folder. + +## Validation commands and acceptance matrix + +Run commands from the repository root. These are implementation-time commands; their inclusion here does not mean the server, scripts, or runtime checks already exist or have passed. + +Before the integration commands, install the built mod and its required DLLs, set `WebSocketApi.Enabled` to true, and restart DSP. Run no-save checks at the main menu, then open a save for `-RequireGame`. For the LAN check, configure the actual LAN bind address or `0.0.0.0` before restarting and connect from the second machine to the server's real LAN address, not to `0.0.0.0`. + +```powershell +dotnet restore LiveStreamAssist/LiveStreamAssist.csproj +dotnet build LiveStreamAssist/LiveStreamAssist.csproj -c Release --no-restore +pwsh -NoProfile -File LiveStreamAssist/tools/Test-WebSocketApi.ps1 -ServerUri ws://127.0.0.1:18080/api/v1 +pwsh -NoProfile -File LiveStreamAssist/tools/Test-WebSocketApi.ps1 -ServerUri ws://127.0.0.1:18080/api/v1 -RequireGame +dotnet build LiveStreamAssist/LiveStreamAssist.csproj -t:ZipMod -c Release --no-restore +git diff --check +``` + +The smoke script must accept those parameters, require no WebSocket client package, close its sockets in cleanup, and exit nonzero when an assertion fails. `-RequireGame` fails clearly if a save is not ready; no-save mode skips only game-dependent assertions, not protocol/system checks. Repeat the relevant script from a second machine with the actual LAN address. A loopback-only run does not establish LAN acceptance. + +Do not use game-mutating debug endpoints to make checks pass. If a particular research ID is needed, discover it from current research, the research queue, or known game data; do not assume the API example's `1001` is always active. + +| Scenario | Required observation | +| --- | --- | +| Default configuration | API disabled, no listener, existing assist still works. | +| Preload / main menu | Ping works; version readiness is explicit; menu demo is not an available player root. | +| Active save | Roots, metadata, research reads, projections, and pages are correct. | +| Pause / text input | Data reads still complete through the Unity context. | +| Space travel | Absent local roots produce `ROOT_UNAVAILABLE`, not a crash or false whole-game failure. | +| Large integer fixture | `Int64`/`UInt64` values beyond JavaScript's safe range round-trip as decimal strings. | +| Forbidden getter / infrastructure | Every resolver path enforces the same policy without invoking the denied code. | +| Cyclic object fixture | Shallow summaries and bounded explicit paths terminate without recursive graph export. | +| Save switch / reload | Old queued requests fail; new queries carry a new session identifier. | +| Invalid / oversized input | Documented JSON error or WebSocket close; no unlimited fragment buffer. | +| Multiple clients / slow consumer | Bounded admission and output; normal clients recover after pressure is removed. | +| Timeout / disconnect / stop | No double completion, leaked slots, stale game references, or Unity-thread wait deadlock. | +| Clean installation | All required third-party DLLs resolve without an incidental mod installation. | +| Existing statistics assist | Ctrl+F8 and automatic tab switching retain their behavior. | + +Normal validation remains the narrow LiveStreamAssist build, with warnings treated as errors under the repository policy. Report unrelated pre-existing failures instead of changing other mods. API-only functionality does not require save-data persistence, a preloader, or changes to the UXAssist public API. + +## Deferred work + +`system.stats` deliberately stops at the placeholder. When statistics are requested, define a concrete schema before enabling `api.stats`; likely candidates are current connections, completed/failed requests, bytes sent/received, and durations in milliseconds since server start. V1 admission counters are resource controls, not an excuse to expose an undocumented metrics schema. + +Subscriptions, writes, method invocation, authentication, additional root catalogs, aggregated gameplay endpoints, dictionary enumeration, and recursive object export require separate scope decisions. Do not implement extension scaffolding for them now.