diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..c13e536 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,17 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Surveillance Client", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build Surveillance Client", + "program": "${workspaceFolder}/managed-client/src/Surveillance.Client.App/bin/x64/Debug/net10.0/Surveillance.Client.App.dll", + "args": [], + "cwd": "${workspaceFolder}/managed-client", + "console": "internalConsole", + "stopAtEntry": false, + "justMyCode": true + } + ] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..dfb26c3 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,25 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build Surveillance Client", + "type": "process", + "command": "dotnet", + "args": [ + "build", + "src/Surveillance.Client.App/Surveillance.Client.App.csproj", + "--configuration", + "Debug", + "-p:Platform=x64" + ], + "options": { + "cwd": "${workspaceFolder}/managed-client" + }, + "problemMatcher": "$msCompile", + "group": { + "kind": "build", + "isDefault": true + } + } + ] +} \ No newline at end of file diff --git a/SurveillancePlugin.exe b/SurveillancePlugin.exe new file mode 100644 index 0000000..0ea11c9 Binary files /dev/null and b/SurveillancePlugin.exe differ diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..7f12b7e --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,1205 @@ +# Installation and setup + +Run REA, connect your selected agents, and check the tools needed for your task. +Setup previews configuration changes and asks for approval before applying them. + +| Task | Section | +| --------------------------------- | --------------------------------------------------------------------------------------------------- | +| Connect an agent | [Start setup](#start-setup), then [review changes](#review-setup-changes) | +| Diagnose one task | [Scoped readiness checks](#check-readiness-for-your-task) | +| Configure an analysis engine | [Hopper](#hopper), [Ghidra](#ghidra), the [IDA guide](ida-provider.md), or [Kuna](kuna-provider.md) | +| Update or remove REA | [Maintenance](#diagnose-update-and-remove) | +| Resolve a client-specific problem | [Client configuration](client-configuration.md) | + +## Start setup + +```bash +npx rea-agents setup +``` + +Choose the agents to configure, review the proposed paths and changes, and +approve the plan. npm's package-download approval and REA's setup approval are +separate. Setup asks before changing agent configuration or installing Hopper. +Restart the agents named in the completion message. Quit Claude Desktop fully +before approving, because a running app can overwrite the registration; on +Windows, see [where Claude Desktop reads its configuration](client-configuration.md#claude-desktop). + +For the latest published release, use `npx rea-agents@latest setup`. +[Package-runner and global-installation options](#package-runners-and-global-installation) +cover explicit versions, Bun, runtime requirements, and the curl wrapper. + +## Review setup changes + +`rea setup` first offers the supported agents in a multi-select. Existing REA +registrations are selected by default. Newly detected clients remain available +but unselected: detection gives setup context, not permission to add a new +registration. Clients without a detected configuration can still be selected. +Explicit `--client` flags skip this question. + +Setup adds MCP access for selected clients. It installs REA's bundled workflow +with those integrations by default; use `--skill=false` to omit it. If no agent +is selected, setup offers the workflow separately for CLI use, with No as the +default. Hopper is a separate optional choice: setup shows its proposed +installation or connection and requires its own explicit approval. It can also +save verified paths for an existing Ghidra installation. + +After selection, review the plan's exact paths and changes and approve before +REA writes files or installs Hopper. You can cancel at any prompt. + +Before applying changes, REA checks your current configuration. The plan lists: + +- an existing Hopper installation, a verified existing Ghidra installation, or the official Hopper package it proposes to install; +- each detected agent configuration path; +- each selected REA skill destination; +- external software, network origins, integrity evidence, and package-manager + commands. + +Malformed or unsafe existing configuration blocks the whole transaction before +Hopper installation or any file write. Declining or pressing Ctrl-C makes no +changes. Agent configuration writes preserve unrelated entries and comments, +create backups, use atomic replacement, and verify their result. Setup and +uninstall retain an existing `.rea.backup` rather than replacing the first snapshot. +If that snapshot differs from the current configuration, setup previews and +preserves a verified `.rea.backup..recovery` copy of the current bytes. +Both snapshots remain available; a failed rollback reports the current recovery +copy's path and the restore failure. +Setup also retains valid environment overrides in REA's existing server entry, +such as `REA_MCP_INPUT_SCHEMA_PROFILE`, `REA_MCP_OUTPUT_SCHEMA_PROFILE`, and +`REA_MCP_MAX_RESPONSE_BYTES`. +Detected provider settings replace only matching environment keys. +Setup and doctor report a malformed REA environment map or invalid runtime +setting before setup writes files. Repair the named setting in the client +configuration; setup does not silently discard the rest of the map. +This includes malformed loader/exclusion JSON arrays and a Ghidra compiler +specification without its required language identifier. Valid overrides keep +their original strings, including empty Hopper arguments. DeepSeek Harness +`!!js` environment expressions remain unevaluated and preserved; registration +alignment does not verify the runtime values those expressions will produce. +For layered OpenCode files, each file's values are checked before merging, while +setting dependencies are checked against the effective merged environment. +Setup preserves each layer's overrides instead of copying inherited settings +into the file it updates. + +After setup, REA reports which agents, analysis tools, and workflow files passed +its final checks. Restart any agent named in the completion message, then begin +your investigation. Failed steps and diagnostics remain in terminal history. + +Select exact clients in scripts with repeatable `--client` flags. Each explicit +client skips interactive selection. Use `--all-detected` only when you intend +to configure every detected supported client. `--skill=false` omits the +workflow, and `--dry-run` returns a read-only plan with status `planned` and +exit code 0: + +```bash +rea setup --client codex --client cursor --skill=false --dry-run +``` + +Prompt UI and progress are written to stderr so stdout remains available for +structured results and pipelines. `NO_COLOR=1` disables color. Use +`--accessible` for sequential, vertically rendered yes/no prompts. Implicit +interactive setup requires stdin, stdout, and stderr to all be terminals; when +any stream is redirected, setup stays non-interactive. Declining or cancelling +returns status `cancelled` with exit code 0. + +For automation, `rea setup --json` reports the plan and a compact `.doctor` +readiness projection without applying it. Use `rea doctor --json` for full +health diagnostics and canonical tool catalog details. Pair +`--yes` with explicit scope such as `--client codex`, or use +`--all-detected` when the broad scope is intended. Without a scope flag, +`--yes` is limited to existing REA-owned registrations; it does not select all +detected clients. An unapproved actual apply reports `needs_confirmation` and +exits 1. Installing missing Hopper non-interactively additionally requires +`--install-hopper`: + +```bash +rea setup --yes --all-detected --install-hopper --json +``` + +### Skill destinations + +The bundled skill is installed in each selected client's personal skill directory. +See [client configuration](client-configuration.md) for client-specific roots, +profiles, and environment overrides. A mixed selection plans each distinct +destination. Selecting the skill without a client uses `~/.agents/skills`. +Setup leaves existing skill copies in other locations untouched. +Setup refuses symbolic links at the selected skill directory or its managed +`references` directory, matching uninstall and update's ownership rules. Use a +regular skill directory, or select `--skill=false` to configure the client +registration without installing the bundled skill. +The final selected directories are checked before approval and again before +setup changes any client or Hopper installation. Unselected client destinations +do not block other setup choices. Doctor reports linked or non-directory skill +paths as `unmanaged`, names the affected paths, and provides those alternatives; +an unreadable skill identity remains `unknown`. Uninstall retains and reports +files it cannot safely remove, including their ownership manifest. + +`rea setup --skill-client claude_code --yes --json` refreshes and verifies the +selected skill destination independently of MCP registration selection. The +final `doctor.scope.skill_clients` records which skill destinations were +checked; `doctor.scope.clients` continues to describe required registrations. +An unselected shared skill does not affect a client-only refresh. + +`doctor --skill --json` verifies the selected copies against the bundled +instructions and references. Consumers should use `identity.skill.state`, +`installed_version`, and `installed_tool_count` for skill readiness. The +obsolete `installed_catalog_digest` field has been removed; current catalog +identity remains available at `identity.catalog`. + +Setup pins package-runner MCP registrations to the exact installed REA version, +installs the matching skill and on-demand references in the same plan, and adds +`startup_timeout_sec = 30` for Codex and Grok Build. Codex also receives a +`tool_timeout_sec` derived from known provider startup plus operation headroom. + +## Limit REA to one project or agent profile + +Setup registers REA for the whole client. For Claude Code it writes +`mcpServers.rea` in `~/.claude.json` and installs the bundled skill under +`~/.claude/skills`, so every project that Claude Code opens can call REA. To +offer REA's tools only where they're wanted, use one of the routes below. + +Both routes control which sessions discover REA's MCP server and skill. They +leave shell commands, filesystem access and network access available. An agent +under the same OS account can run `rea` from `PATH` or `npx` and read other +profiles and REA output. For clean-room separation, use an implementation +environment with filesystem and network restrictions that prevent reading or +fetching REA, the target and analysis output, including through shared +installations and package registries. A separate account or container must +enforce those restrictions. + +For Claude Code, check existing default-profile state before choosing either +route. Setup is additive: a previous user-level REA registration and personal +skill remain active in other projects. Back up the default configuration and +REA skill first, then, with `CLAUDE_CONFIG_DIR` unset, remove the REA user +registration with `claude mcp remove --scope user rea` and remove the known +REA-installed `~/.claude/skills/reverse-engineer-anything` directory. Preserve +unrelated registrations and skills. `rea uninstall` applies to other clients +as well, so it is broader than this Claude-only migration. + +**A separate Claude Code profile.** Claude Code keeps settings, skills and session +history under `CLAUDE_CONFIG_DIR`. Setup follows the same +variable: it writes the registration to `$CLAUDE_CONFIG_DIR/.claude.json` and +the skill to `$CLAUDE_CONFIG_DIR/skills`. +For REA setup, an empty `CLAUDE_CONFIG_DIR` is treated as unset: registration +goes to `~/.claude.json` and the skill goes to `~/.claude/skills`. + +```bash +CLAUDE_CONFIG_DIR=~/.claude-rea npx rea-agents setup --client claude_code +CLAUDE_CONFIG_DIR=~/.claude-rea claude +``` + +A new profile may need authentication. Console sign-ins without an API key are +stored outside `CLAUDE_CONFIG_DIR`; see +[Claude Code authentication](https://code.claude.com/docs/en/authentication#log-in-with-multiple-accounts). +Sessions started without the variable use the default profile's registration, +skill and history. + +Inline assignments apply only to that command. Keep the same prefix for every +profile check, setup rerun, update, or removal; bare commands use the current +environment and can otherwise inspect or recreate default-profile state: + +```bash +CLAUDE_CONFIG_DIR=~/.claude-rea claude mcp list +CLAUDE_CONFIG_DIR=~/.claude-rea npx rea-agents doctor --client claude_code --skill --json +CLAUDE_CONFIG_DIR=~/.claude-rea npx -y rea-agents@latest setup --client claude_code --dry-run +``` + +After reviewing an update plan, rerun that same prefixed setup command without +`--dry-run` and approve its exact changes. Profile removal likewise needs the +prefix on `claude mcp remove --scope user rea` and any `rea uninstall` command; +keep the broader client scope of uninstall in mind. Restart the selected +profile after changing its pinned registration. + +`claude mcp remove` removes only the registration. To remove REA from this +profile without running the broader uninstall flow, first back up the profile's +REA-managed skill directory, then remove +`$CLAUDE_CONFIG_DIR/skills/reverse-engineer-anything` as well. Keep other skills +in the profile intact. + +The commands above use POSIX shell assignment syntax. In native Windows +PowerShell, select the profile for the whole setup/launch/check session and +restore the previous selection afterward: + +```powershell +$previousClaudeConfigDir = $env:CLAUDE_CONFIG_DIR +try { + $env:CLAUDE_CONFIG_DIR = Join-Path $HOME ".claude-rea" + npx rea-agents setup --client claude_code + claude mcp list + npx rea-agents doctor --client claude_code --skill --json + npx -y rea-agents@latest setup --client claude_code --dry-run + # After reviewing the plan, repeat setup without --dry-run and approve it. + claude + # Profile removal, when intended, also belongs inside this selected scope: + # claude mcp remove --scope user rea +} finally { + if ($null -eq $previousClaudeConfigDir) { + Remove-Item Env:CLAUDE_CONFIG_DIR -ErrorAction SilentlyContinue + } else { + $env:CLAUDE_CONFIG_DIR = $previousClaudeConfigDir + } +} +``` + +Use PowerShell for these Windows examples rather than pasting POSIX assignments +into cmd.exe. Keep profile updates, readiness checks and removal inside the +same selected environment; the `finally` block restores the previous profile +or unsets the variable when it was absent. + +**One project.** Install without configuring Claude Code: use the curl +installer's `--no-setup`, or run setup only for other clients. Then register +REA from the project directory at Claude Code's local scope. + +This route uses the default Claude profile. Keep `CLAUDE_CONFIG_DIR` unset for +the entire local lifecycle: registration, backup, listing, version replacement +and removal. In POSIX shells run `unset CLAUDE_CONFIG_DIR`; in PowerShell run +`Remove-Item Env:CLAUDE_CONFIG_DIR -ErrorAction SilentlyContinue` before these +commands. Record an existing selection first if you intend to restore it after +finishing. The configuration path below is the default profile's +`~/.claude.json`; a different active profile uses its own config root instead. + +Register with the variable unset: + + + +```bash +claude mcp add --scope local rea -- npx -y rea-agents@6.5.0 mcp +``` + +On native Windows, use the same project directory and wrap the package-runner +shim so the stdio client can launch it: + +```powershell +claude mcp add --scope local rea -- cmd.exe /d /c npx -y rea-agents@6.5.0 mcp +``` + + + +Local scope stores the entry under that directory's path in `~/.claude.json`, +so other projects don't load it. This route doesn't install the bundled skill. +Avoid `--scope project`, which writes `.mcp.json` into the repository where it +can be committed or copied. `rea doctor` and `rea uninstall` read only the +user-level entry, so they don't report or remove a local-scope registration; +remove it with `claude mcp remove --scope local rea` from the same directory. +`rea update` doesn't refresh it either, so it stays on the version it names. +To move it to a newer release, first back up the project entry in +`~/.claude.json` and record its environment and other metadata. In particular, +preserve caller-selected overrides such as `REA_MCP_INPUT_SCHEMA_PROFILE` and +`REA_MCP_MAX_RESPONSE_BYTES`. Run `claude mcp remove --scope local rea` from the +same directory, then recreate it with the platform-appropriate command above +and the new version. Reapply every recorded environment value with Claude +Code's `mcp add --env NAME=value` options and restore any other retained entry +metadata before restarting the project session. Removal and re-addition do not +preserve these values automatically. Running setup for Claude Code instead +would add a user-level entry for every project. + +Check the separate profile with the prefixed `claude mcp list` above and compare +with the default profile with `CLAUDE_CONFIG_DIR` unset. For local scope, run +`claude mcp list` from the selected project and again from another project. + +## Check readiness for your task + +Run `rea doctor` when you need diagnosis. It reads host prerequisites and agent +configuration without changing them. Without options, it audits every detected +registration, the installed skill and optional analysis engines; its overall +`healthy` value can be false while your chosen workflow works. + +Doctor's `providerInspections` are host-level engine and registration checks, +not a readiness row for every advertised MCP adapter surface. `tools/list` +remains the complete stable catalog. Call `binary_session` with `{}` before +choosing an operation; it works before a target is opened, and +`result.tool_availability` reports per-operation availability, reasons and +client requirements for the current session state. It does not guarantee that +a particular caller-supplied input will be valid. See +[MCP discovery](mcp-contracts.md#identity-and-discovery). + +Select the part you want to check: + +| Task | Readiness check | +| ----------------------------------- | ------------------------------------------------------------------------ | +| Static JavaScript/Electron analysis | Run `rea analyze-javascript-application PATH --json` directly. | +| One analysis engine | `rea doctor --provider ghidra --json` (or `hopper`, `ida`) | +| One agent registration | `rea doctor --client codex --json` (see [client IDs](#supported-agents)) | +| Installed workflow instructions | `rea doctor --skill --json` | + +A scoped report has `scope.mode: "explicit"`. Its `scope_checks` determine +`healthy` and the exit status. Other checks appear in `informational_checks`; +`environment_healthy` summarizes the full audit. `--target` adds a target check, +but the report remains audit-wide unless a scope option is also supplied. + +Follow the remediation for the failed check. If a native target has several +available providers, choose one with `--provider` on the CLI or `provider_id` +on `open_binary`. A `capability_unavailable` failure carries +`details.selection_reason`: `ambiguous` asks you to choose from +`details.candidate_ids`, while `provider_unavailable` asks you to repair the +selected engine. See [provider selection](cli.md#choose-a-provider). + +### Linux owned-process prerequisite + +On Linux, REA's shared process supervisor requires a procps-compatible `ps` +on REA's `PATH` for ownership checks before launching a child. Ghidra, JADX, +firmware tools and static JavaScript/Electron analysis use these checks. +Install your distribution's `procps` or `procps-ng` package, or put another +procps-compatible `ps` on `PATH` before +running those workflows. A missing or incompatible command causes a refusal +before the supervised child starts. + +The public error code varies by caller: `capability_unavailable`, +`provider_unavailable` or `execution_failure`. Some provider adapters report +only a generic startup error. Check this prerequisite before following +provider-specific recovery advice. + +## Diagnose, update, and remove + +`rea doctor --json` is strictly read-only. `rea update` updates only the npm or Bun global installation that owns the running CLI. Source checkouts and package-runner copies must be updated through the mechanism that owns them; a fresh package-runner invocation can use `npx rea-agents@latest` or `bunx rea-agents@latest`. `rea uninstall` removes only REA-owned agent registrations and skill files; `--purge-data` additionally removes REA cache and state paths. + +```bash +rea update +rea uninstall +rea uninstall --purge-data +``` + +Uninstall preserves Hopper, Node.js, Evidence files, captures, unrelated skills +and other MCP servers. Purging removes only REA's cache and state under +`~/.rea`. A client configuration that is malformed, unreadable, or at an unsafe +path stops the operation before anything is removed, and a client that fails +while being updated stops the remaining removals. A purge path that is a +symbolic link is retained and reported rather than followed. Uninstall checks +REA's managed shared and Claude Code personal skill locations. See the +[CLI guide](cli.md#output-and-exit-status) for exit statuses. + +### Update the owning installation + +`rea update` installs the exact resolved +release into the npm prefix or Bun global directory that owns the running +package, then checks the new executable's version before reporting success. It +does not reopen onboarding. For npm installations, release lookup and +installation both use npm's configured registry. Bun global updates require +Bun 1.2.17 or later, which introduced `bun info`. The updater checks `bun --version` +first and stops with an instruction to upgrade Bun manually if the version is +older or cannot be parsed; it does not upgrade Bun itself. +For supported Bun global installations, `bun info` and +`bun add --global --ignore-scripts` use Bun's configured registry +and run inside the owning Bun global directory (`BUN_INSTALL_GLOBAL_DIR`, else +`$BUN_INSTALL/install/global`, else `$XDG_CACHE_HOME/.bun/install/global`, +else `~/.bun/install/global`), never in the caller's current project. A Bun +global directory without its `package.json` is not treated as an owned +installation, because Bun would install into the nearest ancestor project +instead. +Its maintenance plan selects only existing REA registrations and an already +installed REA skill. Run the returned scoped setup command to review and approve +those changes, then restart affected agents. The plan is returned in terminal, +non-TTY, and JSON modes without applying configuration changes. + +## Released package and main + +Repository main documents its current code and generated catalog. `@latest` +selects the npm release, and persistent MCP registrations are pinned to the +version that performed setup. Installing newer instructions does not update a +running server or its registration. + +The npm release checked on **2026-10-11** was **6.4.0**, published from +[`a56f7bb6`](https://github.com/morluto/rea/commit/a56f7bb668ab23fec8d33f7af353ac7ed2fe1895). +The actual registry package accepted dry-run setup plans for the 17 client IDs +in that release, including Qwen Code, Pi and Hermes. Seven client IDs are +included from 6.5.0 and were absent from the checked npm 6.4.0 package: `droid`, +`dsh`, `kimi`, `qoder`, `trae`, `workbuddy` and `zcode`. +The 6.4.0 registry check does not establish 6.5.0 publication or live DeepSeek +API integration. +OpenCode's plan selected +`OPENCODE_CONFIG_DIR` even when that directory did not yet exist. These checks +used an isolated home on macOS with Node 24; they verify planning and argument +admission, without writing client configuration or establishing live integration +with every client. This resolves the npm 6.3.0 setup gaps tracked in +[#1650](https://github.com/morluto/rea/issues/1650). + +Main's catalog describes the current code. A source build or a subsequent +release containing changes after this checkpoint is required for newer +functionality. Package startup alone does not verify a provider's real +platform workflow. + +To check the published version, run `npm view rea-agents dist-tags.latest`. +Use the connected server's actual tool list and advertised input schemas for +feature selection. The same package version string in a development checkout +does not establish that its bytes match the npm tarball. Update a registration +through a reviewed, scoped setup plan, then restart/reconnect the agent. + +## Skill-only installation + +```bash +npx skills add morluto/rea --skill reverse-engineer-anything +``` + +This installs agent instructions and bundled references, not REA MCP +registration or analysis engines. Follow the skill's +[conditional connection guide](https://github.com/morluto/rea/blob/main/.agents/skills/reverse-engineer-anything/SKILL.md#connect-only-when-needed). +Working tools can be used immediately. If tools are missing, inspect the current +client's registration with `doctor --client codex --json` (substitute its client +ID), then plan repairs with `setup --client codex --dry-run --json`. Show and +approve the exact changes before applying that scope. An aligned registration +with tools absent from the active session needs a restart/reconnection; +`doctor` checks files and prerequisites, not the live agent connection. + +Guided setup installs the package's matching skill by default. The skills.sh +route can select newer repository instructions, so follow actual server schemas +and the release boundary above. Static JavaScript CLI inspection can proceed +while MCP is unavailable: + +```bash +npx -y rea-agents@latest analyze-javascript-application /absolute/path/to/app --json +``` + +It returns the complete Evidence record directly and requires no native engine. +Provider failures in doctor do not prevent unrelated target-free tools. To check +readiness for one task instead of auditing every integration, see +[Check readiness for your task](#check-readiness-for-your-task). + +## Supported agents + +Setup can configure these clients for REA's local MCP server. Grok Bot uses a manual +hosted connector; see [its configuration](client-configuration.md#other-client-settings). + +| Client | `--client` value | +| ------------------ | ---------------- | +| Claude Code | `claude_code` | +| Claude Desktop | `claude_desktop` | +| Codex | `codex` | +| Cursor | `cursor` | +| Gemini CLI | `gemini_cli` | +| Windsurf | `windsurf` | +| Devin | `devin` | +| OpenCode | `opencode` | +| Antigravity | `antigravity` | +| GitHub Copilot CLI | `copilot_cli` | +| Command Code | `commandcode` | +| Qwen Code | `qwen_code` | +| Kimi Code | `kimi` | +| VS Code | `vscode` | +| Grok Build | `grok_build` | +| OMP | `omp` | +| Pi | `pi` | +| Hermes | `hermes` | +| Qoder | `qoder` | +| Factory Droid | `droid` | +| Trae | `trae` | +| WorkBuddy | `workbuddy` | +| ZCode | `zcode` | +| DeepSeek Harness | `dsh` | + +`droid`, `dsh`, `kimi`, `qoder`, `trae`, `workbuddy`, and `zcode` require +`rea-agents@6.5.0` or later. The 6.4.0 registry check above does not cover them. + +See [client configuration and troubleshooting](client-configuration.md) for +configuration paths, profiles, trust policies, and schema-limit workarounds. + +### DeepSeek Harness + +See [the Cordis patch and launcher setup](client-configuration.md#deepseek-harness). + +### Other client settings + +See [OpenCode, Grok Build, and Grok Bot settings](client-configuration.md#other-client-settings). + +## Hopper + +Hopper is separate commercial software with its own license. Its free demo has +vendor-defined limits, and a paid license is optional. REA reuses any detected +installation and preserves Hopper during uninstall. + +The automated Hopper installer supports macOS 12+, Ubuntu 24.04+, Fedora 41+, +Nobara 44+, 64-bit Arch Linux, CachyOS, or Omarchy. REA itself runs on any +Linux distribution with a recognized apt, dnf, or pacman package family, where +an existing Hopper launcher is selected through `HOPPER_LAUNCHER_PATH`. Ghidra +and IDA have their own provider-specific host requirements; Windows Ghidra uses +the [experimental P0 boundary](windows-ghidra-p0.md). + +On macOS, approved setup downloads the official DMG, checks its published size +and digest, validates the application bundle, and atomically installs it to +`~/Applications/Hopper Disassembler.app`. REA then opens Hopper so the +operator can choose its demo mode or activate an existing license. Homebrew and +administrator access are not used. + +The Hopper launcher action used by REA creates a document from an executable; +its supported command-line interface does not attach to an already-open +document. While another live REA session owns the same target and loader +profile, a second session reports the owning run ID instead of opening a +duplicate document. On macOS, closing the owning REA session releases this guard; +Hopper keeps its document open. A later REA session can therefore open another +document for the same target. REA does not currently identify, focus, or reuse +that existing GUI document, and the supported launcher exposes no attach or +reuse action for it. + +REA currently declines saved Hopper database (`.hop`) targets on macOS because +the native `open database` launch route does not run REA's bridge script. To +analyze that program with REA, select its original executable as the target and +open it through Hopper; this starts the supported bridge route. This does not +recover database-only annotations or analysis changes. Saved-database analysis +on Linux continues to use its supported demo-launch route. + +Hopper lease directories must be readable and owned by the current user. +REA validates and secures an opened directory before reserving a lease. If +opening that directory fails with a permission error, the diagnostic identifies +the path and recovery steps while leaving its permissions unchanged. Check +ownership and parent-directory access, then restore owner-only read, write, and +search permissions (`0700`) on a directory you own before retrying. + +On supported Linux distributions, approved setup verifies Hopper's official +`.deb`, `.rpm`, or Arch package before invoking the native package manager. +The official release feed selects the current public demo without a version +pin. REA verifies the package's detached PGP signature against Hopper's stable +primary fingerprint `7C2D73BAFAF5B9A710A69DA1A26DF815099B1BCD`, then checks +that the signed package and installed launcher agree with `main_exe_hash`. +Rotating signing subkeys remain bound to that primary identity. +The feed row itself is not PGP-signed; doctor labels its display version as +`reported_release_version`, separately from the authenticated launcher identity. + +The approval plan includes the caller-selected cache location. Approved setup +retains the signed archive, public key and release metadata under +`${XDG_CACHE_HOME:-$HOME/.cache}/rea/hopper-releases/`. +An empty `XDG_CACHE_HOME` uses `$HOME/.cache`. Approved setup can repair a +damaged caller-owned entry after authenticating a fresh package; the previous +entry is preserved beside it as `.backup-`. Ordinary doctor +and launches reject damaged evidence and never repair it implicitly. +Approved publications of the same canonical cache entry share a process-backed +lease. Concurrent setup waits without moving another writer's evidence; a +failed replacement restores the previous directory when possible and reports +any retained backup path. Unavailable reads or native inspection tools do not +authorize replacing existing evidence. +Doctor and launches authenticate this evidence for offline use; an editable +digest receipt alone cannot authorize a launcher. Verification reuses at most +eight immutable package proofs per process, keyed by the complete package, +key, signature, package format and expected launcher digest. Cached file reads +still check identity and content. Without retained evidence, inspecting an +existing install requires the matching current official package and network +access. Successful live inspection can be reused within that process after +rehashing the launcher; it does not write a persistent cache or claim that a +previously observed release is still the latest. Older uncached builds require +an approved update while the feed exposes only its current release. + +REA runs the supported demo build on a private Xvfb display and selects Hopper's +offered demo mode for each analysis session; it does not require the user's +desktop display. Unattended package-manager access requires +`--yes --install-hopper`. If the host exposes `/tmp/.X11-unix` as an immutable +mount, REA first verifies the conflict and then uses an unprivileged user and +mount namespace with a private mode-1777 tmpfs over that directory only. The +host mount and the rest of `/tmp` remain unchanged; this fallback never invokes +`sudo`. `rea doctor --provider hopper --json` reports the selected +strategy and both host and effective mount facts. + +When the package-manager step fails, setup reports the failing command and its +captured output, so a package conflict is distinguishable from an authorization +failure. On CachyOS, an unversioned compatibility package such as +`zlib-ng-compat` may conflict with Hopper's versioned `zlib` dependency. Resolve +the package conflict yourself or install Hopper's official package manually, +then rerun `rea setup`. + +The supported Linux demo forwards additional launches into its existing +application, even across private displays. REA therefore reserves one Linux +Hopper application per user across cooperating REA processes. A competing +CLI or MCP session receives the owning session ID before Hopper is launched, +for both the same target and a different target. Switch targets through that +MCP session, or close it before starting another session. Closing the owner +releases the reservation and stops REA's owned demo application and private +display; the headless Linux demo does not retain documents after MCP shutdown. +Its helper watches a private lifetime pipe, so an owner crash or SIGKILL also +stops those children, without relying on a reusable PID or a process-name scan. +A later session recovers the dead owner's stale lease after child cleanup; +private runtime files can remain when REA itself was killed. This does not attach to +or claim ownership of manually opened Hopper applications. An application left +running by an older REA version must still be closed before starting a new session. + +Stale lease recovery is serialized. If an interrupted recovery leaves its +reservation directory, the diagnostic identifies that exact path. Stop REA +sessions before removing that recovery directory and retrying. + +### Launcher paths and troubleshooting + +On macOS, REA checks executable Hopper launchers in this order: the canonical +system application, the canonical application installed by `rea setup` under +`~/Applications`, then other `Hopper*.app` bundles in `/Applications` and +`~/Applications`. The Homebrew cask location is an optional `rea doctor` +diagnostic; to use a Homebrew-installed launcher for CLI/MCP startup, set +`HOPPER_LAUNCHER_PATH` to the path reported by doctor. REA does not run Homebrew +while loading runtime configuration. +Automatic discovery accepts executable regular files, including file symlinks, +and skips directories. +On Linux, it prefers executable `/opt/hopper/bin/Hopper`, then executable +`~/.local/share/rea/hopper/bin/Hopper`, followed by `/opt/hopper-v4/bin/hopper` +and `/usr/bin/hopper`; if none exists, the former remains the diagnostic +fallback. `HOPPER_LAUNCHER_PATH` overrides those choices: + +```bash +export HOPPER_LAUNCHER_PATH=/absolute/path/to/Hopper +rea doctor --provider hopper --json +``` + +Hopper startup allows 120,000 ms for launch, initial analysis, and authenticated +bridge readiness. For large targets, set `REA_HOPPER_STARTUP_TIMEOUT_MS` to a +decimal integer from 1 to 2,147,483,647 milliseconds in the environment that +starts REA. CLI and MCP use the same setting; invalid values fail configuration +validation. An MCP client's own request timeout must also allow enough time. +`open_binary` validates and selects a target without waiting for native provider +readiness. During Hopper startup, `binary_session.provider_operation_health` +reports `busy` at stage `launch`; `analysis_activity` describes bridge requests +and can remain idle until the socket is ready. Cleanup work reports `busy` at +stage `connection`. + +If macOS denies Apple Events, allow the application that starts REA under +**System Settings → Privacy & Security → Automation**, then retry. REA releases +the target reservation when the native helper reports its complete authorization +rejection and its arguments cannot alter the helper's generated AppleScript. +Arguments containing quotes, backslashes, or line breaks remain unchanged but +cannot establish that a failed handoff opened no document. Other failed handoffs +retain ownership until document closure is confirmed. If a timed-out bridge +becomes ready later, `close_binary` connects to that run, authenticates its +identity, and requests document shutdown. Once its listener is ready, the bridge +allows 30 seconds for the first connection and capability validation. After a +connection drops, it allows the same grace period for an authenticated cleanup +reconnect, then releases Hopper's Python execution thread. Initial analysis is +outside this listener grace period, and authenticated native work is not bounded +by it. Expiry does not establish document closure, so REA +retains unconfirmed ownership. Retry close while the bridge remains available. + +If a Linux launcher exists but cannot start, inspect its shared libraries: + +```bash +ldd /absolute/path/to/Hopper | grep 'not found' +``` + +Install the missing packages and rerun the scoped check. Linux demo sessions +need Xvfb, Python 3, X11 and XTEST; approved setup installs those dependencies +on supported distributions. Add the curl installer's reported executable +directory, commonly `~/.local/bin`, to your shell `PATH` if needed. + +REA starts Hopper when needed. On macOS, complete its demo or license prompt in +the same user session before the first CLI/MCP operation or unattended job. Open +Hopper manually if needed; its launcher can also bring the dialog forward. +If startup reports `Cannot launch Hopper! Connection is invalid.` or waits for +bridge readiness, check Hopper for a pending demo, license, or loader dialog. +Complete the dialog and retry. If REA reports `cleanup_incomplete`, follow the +retained-resource guidance below before reopening the target. + +On macOS, Hopper can show an `Executing Python Script...` overlay while the REA +bridge serves an active MCP connection. Long-lived MCP clients can keep that +connection open across agent turns, so the overlay may remain visible after the +analysis calls finish; by itself, it does not establish a stalled startup. REA +does not automatically idle-close a still-connected target. When the +investigation is finished, export an Evidence bundle first if you need to keep +the session ledger, then call `close_binary`; set `snapshot_path` to save a +provider-neutral analysis snapshot as part of closing. A successful close +shuts down the REA bridge and clears its overlay; REA does not control the +macOS Hopper application lifetime. +The Hopper GUI Cancel button's behavior for this bridge has not been verified; +`close_binary` is the supported cleanup path. + +Hopper serializes analysis requests. Cancelling a wait can leave provider work +running, which the session reports. Successful decompilation is cached until +a relevant rename or comment changes it. + +Analysis and annotation calls stay bound to the active target's native Hopper +document, even when GUI focus changes or other documents have the same display +name. Use `open_binary` to change targets. Byte reads stop at a segment boundary +and return the readable prefix with `complete: false`. File-offset mapping checks +the reverse lookup and original executable bounds; synthetic external-symbol +memory has no original file offset. For FAT Mach-O, offsets refer to the original +container file. Results retain Hopper's image-relative offset, the observed slice +base, and the source executable path. +Loader selection reads the Mach-O container header, including FAT files with a +single architecture. For FAT32 and FAT64 containers, REA validates the +architecture table and selected Mach-O header, prepares a private thin image, +and loads it with Hopper's native Mach-O loader instead of Hopper's implicit +FAT slice choice. For arm64 targets, REA ranks subtype bases 0 (plain arm64) and +2 (arm64e), ignoring capability bits for ranking while retaining the raw subtype +for slice identity. These slices' function-entry encodings decode under +`--aarch64`, ahead of Apple's arm64e.x1 variant (base subtype 12), which is +selected only when it is the arm64 family's only candidate. REA checks the +entire source's SHA-256 while copying the slice; source identity and reported +offsets still refer to the original container. Any other ambiguous architecture +subtype requires an explicitly extracted thin image; REA does not guess. +Configured loader arguments remain explicit overrides. +FAT64 is distinct from the CPU architecture: FAT32 containers can contain 64-bit +executable images. This preparation avoids the Raw Binary loader dialog observed +with native FAT64 loading on Hopper 6.1.0-demo. +The prepared image and its owned document close together, including on MCP exit; +if document closure is unconfirmed, REA retains the backing image and reports +`cleanup_incomplete` with its path. Ordinary documents retain their existing +MCP-exit behavior. +Startup deadlines report missing bridge readiness and preserve the launcher +outcome; a successful helper exit does not prove that a loader dialog completed. +If an owned provider process exits, request failures preserve its observed exit +code or signal and bounded output in `details.launcher`. An exit can precede +output-stream closure; `output_closed: false` keeps that uncertainty explicit. +Later requests retain the known exit instead of reducing it to socket loss. +An external GUI's helper exit does not establish that the GUI itself exited. +For cursor navigation, string decoding, symbol-name limits, and regex matching, +see [Hopper analysis behavior](native-investigation.md#hopper-analysis-behavior). + +Closing or switching a target closes its bound Hopper document, shuts down REA's +bridge and removes its temporary socket directory. The macOS Hopper application +and unrelated documents remain open; the owned Linux demo application stops. +A `cleanup_incomplete` +result identifies resources whose cleanup could not be verified. +REA retains unresolved cleanup ownership and any confirmed shutdown phases. +After addressing the reported failure, retry `close_binary` on the same +connection. Unconfirmed document or process cleanup retains the target/application +lease and prevents another client from launching against that owned resource. +Once document and process closure are confirmed, the lease can be released even +if temporary-file cleanup fails. Another client can then launch, but the owning +client must finish its retained cleanup before starting again. +An unconfirmed external document can be retried while its authenticated bridge +remains available. The same authentication and process-identity capture apply +when the first successful handshake occurs during cleanup after a startup +timeout. REA can confirm closure if that exact authenticated process exits, +including while a shutdown request is in flight. A helper exit alone is +insufficient, and an application that never authenticated has no verified +process identity. If no matching bridge becomes available, inspect and close +the reported document in Hopper before ending the owning REA connection. +Export the Evidence bundle before `close_binary` clears session records. +`binary_session.cleanup_pending` remains true while provider cleanup is retained, +and provider health remains visible even with `open: false`; that flag alone +does not establish successful cleanup. + +### Hopper in CI + +REA's unattended Linux path is validated against Hopper's offered demo mode. +A paid license is not required for that path, and REA does not read, install, or +automate license credentials. Licensed Hopper installations remain supported, +but license activation is an operator-owned prerequisite rather than part of +REA setup. + +macOS requires Hopper's first-run UI to be completed in the same user session +that will run REA: choose the demo mode or activate an existing license before +starting an unattended job. Ephemeral macOS runners therefore need a +pre-provisioned user session or a deliberate interactive bootstrap step. + +When Hopper cannot start in CI, run +`rea doctor --provider hopper --json` in the failing runner. +Structured failures distinguish private-display dependencies, an unsupported +demo dialog or build, process-ownership conflicts, and an early lifecycle exit. +Apply the reported remediation rather than exposing the runner's desktop, +copying license secrets into logs, or killing unrelated Hopper processes. + +## Ghidra + +REA connects to an existing Ghidra installation on Linux x64/arm64, macOS x64/arm64, +or experimental Windows x64 P0. +It accepts Ghidra 12.1.x and the 64-bit full JDK declared by that installation's +`application.java.min` and `application.java.max`. The JDK's reported platform must also +map to the same native decompiler directory as the host: a JDK running under +emulation (for example x86_64 under Rosetta on Apple silicon) or reporting a +non-host `os.name` fails the doctor +even when it is an otherwise accepted 64-bit full JDK. Select a matching JDK +through `JAVA_HOME`; adding another decompiler in the JVM-selected directory +does not satisfy this host-validated admission rule. Current 12.1 releases require +JDK 21 or newer and set no maximum. The bridge is verified with Ghidra 12.1.4 +and JDK 21. Each installation must include the native decompiler for the host +architecture in `Ghidra/Features/Decompiler/os//` or the corresponding +`build/os//` directory. Linux ARM64 uses `linux_arm_64`; official +release archives may require you to build that native component separately. +REA checks the executable prerequisite by inspecting the file's own executable +header, so a native component built for another platform or architecture is +reported as incompatible instead of being admitted from its directory name, and +a header that cannot be read or recognized is reported as unknown. REA does not +build or install native tools, or change Gatekeeper quarantine settings. + +The adapter exposes 26 read-only operations: fourteen inventory/name/search +operations and twelve function-analysis operations. These cover metadata, +decompilation, assembly, resolved calls, typed references, xrefs, function +dossiers, instructions, recovered data types, measured load mappings, loaded +memory bytes, and observed file offsets. Independent load-image attestation +supports DOS MZ, explicitly selected COM, and explicit raw-binary imports; +PE returns measurements with an unsupported attestation status. +On Linux and macOS, `annotate_native_function` also edits a function name and/or +entry comments atomically and returns refreshed analysis, and `set_address_name` +and `set_addresses_names` name a function entry or any other mapped address +(creating or renaming its primary label) with per-address success results. These +session metadata edits leave executable bytes unchanged and are discarded on close. GUI controls +require Hopper; Windows P0 remains read-only. + +Windows P0 admits native x86, x86-64, ARMNT (Thumb-2) and ARM64 PE applications and DLLs, plus explicitly +selected [raw NMOS 6502 images](raw-binary.md#nmos-6502) with a caller-supplied +entry at file offset 0, on fixed local NTFS volumes. Other raw CPU families remain +unsupported on Windows. +The npm package bundles native Job Object ownership, protected private runtime +DACLs, and handle-based path admission; no separate addon installation is needed. +See the [Windows Ghidra P0 guide](windows-ghidra-p0.md) for verified scope and +limitations. + +Extract Ghidra and install the JDK outside REA, then export absolute paths: + +```bash +export GHIDRA_INSTALL_DIR=/absolute/path/to/ghidra_12.1.4_PUBLIC +export JAVA_HOME=/absolute/path/to/jdk-21 # optional if java/javac are on PATH +rea doctor --json +rea setup +``` + +On Windows, configure the existing installation in PowerShell: + +```powershell +$env:GHIDRA_INSTALL_DIR = "C:\tools\ghidra_12.1.4_PUBLIC" +$env:JAVA_HOME = "C:\Program Files\Java\jdk-21" +rea doctor --json +rea providers --json +``` + +`rea setup` can configure supported Windows agents and install the bundled +REA skill after approval. Direct registrations use Node to launch REA's entry +script; package-runner registrations use the pinned `npx` or `bunx` command. Hopper +installation remains unavailable on Windows. Setup never installs Ghidra, +Java, or Python. It preserves valid detected Ghidra/JDK settings in agent +registrations. See [Windows Ghidra P0](windows-ghidra-p0.md) for provider diagnostics. + +When `GHIDRA_INSTALL_DIR` is unset, doctor and the Ghidra provider also search +`PATH` for `ghidra` or `ghidraRun`, resolve the selected launcher through its +real path, and accept it only when that location belongs to a Ghidra tree with +the application metadata and headless launcher. An explicitly supplied +`GHIDRA_INSTALL_DIR` always takes precedence, including when it is invalid; +REA reports that error instead of silently selecting another installation. +This discovery is read-only and does not execute the Ghidra launcher. + +Doctor validates the platform, architecture, Ghidra 12.1.x application version, +`support/analyzeHeadless` or `support/analyzeHeadless.bat`, the installation's +Java major range, 64-bit JDK bitness, and the presence of `javac`/`javac.exe`. +It also checks that the reported JVM `os.arch` and `os.name` map to the same native decompiler +directory validated for the host; unrecognized reported architectures or a +non-host operating system are refused. LaunchSupport overrides of either +property, including through helper-environment JVM option variables, are +rejected at launch. +When Java is found through `PATH`, setup records its observed JDK home so GUI +MCP clients do not depend on an incidental shell path. Setup shows every exact +environment entry in its plan, writes only after approval, and never downloads, +installs, upgrades, or modifies Ghidra or Java. + +Each verified session uses an ephemeral temporary project and isolated +home/cache/config/temp paths. REA passes `-readOnly`, `-deleteProject`, uses +Ghidra's default analysis settings, and loads its packaged Java +bridge via `-scriptPath`; it never opens an existing user project. Linux and +macOS use a current-user-only local bridge socket and descriptor. The +project remains under the selected temporary directory. If its Unix socket +pathname would exceed the host's byte limit, REA allocates a separate owner-only +socket directory under `/tmp` and removes it on close, cancellation, or failure. +Diagnostics retain the actual endpoint and both owned directories. +On Linux and macOS, REA starts the inspected JVM directly using Ghidra's own LaunchSupport +configuration. Apple platform shell wrappers hide their environments from +ownership inspection, so retaining those wrappers would prevent verified +process-group cancellation during startup. +If ownership remains unverifiable, it reports the reason and retains the process +supervisor and private runtime instead of removing files beneath a live provider. +The experimental Windows transport uses authenticated IPv4 loopback with a +private native-owned bearer descriptor and Job Object process ownership. + +Operations begin only after default auto-analysis completes. `open_binary` +selects and validates the target/provider binding; it does not wait for Ghidra +import and auto-analysis. The first Ghidra-backed query starts that work lazily. +The provider startup deadline is 330,000 ms by default for import, analysis, +bridge, and health readiness. Large binaries can need more: set +`REA_GHIDRA_STARTUP_TIMEOUT_MS` to an integer between 1 and 2,147,483,647 +milliseconds in the server environment. An absent setting uses the default; +empty, invalid or out-of-range supplied values fail configuration validation. +REA parses the supplied configuration environment and +passes the deadline to each provider client; a startup failure is returned by the query that triggered it, +without exposing partial analysis. This deadline is separate from MCP transport +initialization and the client's deadline for that individual tool call. A client +can time out earlier even when Ghidra would complete within its startup deadline. +See [Ghidra first-query deadlines and recovery](mcp-contracts.md#ghidra-first-query-deadlines-and-recovery) +for client options and the close/reopen recovery flow. + +One session contains exactly one imported Program; use `provider_id: "ghidra"`, `--provider ghidra`, or +`REA_ANALYSIS_PROVIDER=ghidra` when both Hopper and Ghidra support the target. +One persistent decompiler is owned by the Program, and a serial queue keeps +Ghidra API calls on the owning Program thread without a fixed queue length. +Operations run until a result, caller cancellation, or provider shutdown; there +is no fixed per-operation or response-size ceiling. Unresolved computed calls +remain unknown, reference-kind provenance is preserved, and provider-specific +pseudocode is never treated as original source or Hopper-equivalent text. + +### Missing macOS native decompiler + +If `rea doctor --json` reports `native_decompiler` as missing on macOS x64, +the extracted Ghidra archive may include the decompiler source without the +macOS executable. For Ghidra 12.1.4, you can build it manually with an existing +Xcode Command Line Tools installation, `make`, and `bison`: + +```bash +cd "$GHIDRA_INSTALL_DIR/Ghidra/Features/Decompiler/src/decompile/cpp" +make ghidra_opt +decompiler_dir="$GHIDRA_INSTALL_DIR/Ghidra/Features/Decompiler/os/mac_x86_64" +mkdir -p "$decompiler_dir" +test ! -e "$decompiler_dir/decompile" && test ! -L "$decompiler_dir/decompile" && + install -m 755 ghidra_opt "$decompiler_dir/decompile" +rea doctor --json +``` + +The copy step requires the destination to be absent and preserves an existing +decompiler. This recipe is specific to macOS x64: the +[Ghidra 12.1.4 Makefile](https://github.com/NationalSecurityAgency/ghidra/blob/Ghidra_12.1.4_build/Ghidra/Features/Decompiler/src/decompile/cpp/Makefile) +explicitly selects `-arch x86_64` on Darwin. For a Gradle +build, follow the matching release's +[native component instructions](https://github.com/NationalSecurityAgency/ghidra/blob/Ghidra_12.1.4_build/GhidraDocs/GettingStarted.md#building-native-components). +REA accepts the matching executable under either `os//` or +`build/os//`; it does not build the component during setup or diagnosis. + +### macOS arm64 native decompiler + +On Apple Silicon the same source build works with explicit overrides; no +Makefile edits and no Rosetta are needed. The Darwin block in the +[Ghidra 12.1.4 Makefile](https://github.com/NationalSecurityAgency/ghidra/blob/Ghidra_12.1.4_build/Ghidra/Features/Decompiler/src/decompile/cpp/Makefile) +pins `-arch x86_64`, but `ARCH_TYPE` and `OSDIR` are ordinary make variables, +and command-line assignments replace them for every compile and link rule: + +```bash +cd "$GHIDRA_INSTALL_DIR/Ghidra/Features/Decompiler/src/decompile/cpp" +make ghidra_opt ARCH_TYPE="-arch arm64" OSDIR=mac_arm_64 +decompiler_dir="$GHIDRA_INSTALL_DIR/Ghidra/Features/Decompiler/os/mac_arm_64" +mkdir -p "$decompiler_dir" +test ! -e "$decompiler_dir/decompile" && test ! -L "$decompiler_dir/decompile" && + install -m 755 ghidra_opt "$decompiler_dir/decompile" +rea doctor --json +``` + +Verified end to end on macOS 15.6 arm64 with Apple clang 17 and the stock +bison 2.3, against Ghidra 12.1.4: the build produces a Mach-O arm64 +`ghidra_opt`, the doctor check `ghidra-native_decompiler` turns healthy with +"reports mach-o arm64, which matches darwin/arm64", and `rea decompile` on an +arm64 Mach-O returns decompiled C through the headless provider. The JDK is +not needed for the make step, only for the Ghidra provider. If your toolchain +rejects the inherited `-mmacosx-version-min=10.6` flag, retry the make with +`ADDITIONAL_FLAGS="-w"`. + +### Ghidra import language and analysis seeds + +Ghidra detects the language from the executable header. To set it (for example, Borland C++ PE images): + +```bash +export REA_GHIDRA_LANGUAGE_ID="x86:LE:32:default" +export REA_GHIDRA_COMPILER_SPEC_ID="borlandcpp" # optional; requires a language +``` + +REA passes `-processor`/`-cspec`, checks both against the installation's `.ldefs`, and records them in the analysis profile. DOS imports reject an override. + +To seed code that auto-analysis cannot reach (computed jumps, pointers in data): + +```bash +export REA_GHIDRA_SEED_FILE=/absolute/path/to/seeds.tsv +``` + +Each line is `addresskind[name]`, where kind is `function`, `code` or `label` (a label needs a name). Addresses are `0x` hex in the default space; `#` lines are comments. A pre-script applies seeds before auto-analysis: functions from the highest address down, then code, then labels. The seed digest is part of the analysis profile, and the session fails if the applied seeds differ. Result limitations report the outcome counts; a seed fails when it overlaps an instruction Ghidra already decoded. + +Label seeds can name mapped uninitialized storage such as `.bss`; function and code seeds require initialized bytes. + +To skip a named Ghidra auto-analyzer (for example, when default auto-analysis +stalls in one analyzer on a Swift/Objective-C arm64 Mach-O): + +```bash +export REA_GHIDRA_DISABLED_ANALYZERS="Objective-C Message Analyzer" +``` + +The value is a comma-separated list of exact Ghidra analyzer names. A pre-script +disables each name before auto-analysis, the analysis profile records the +override in `analyzer_preset` (for example +`ghidra-default+disabled:Objective-C Message Analyzer`), and a session fails to +open when its committed profile and the setting differ. A name starts with a +letter or digit and contains only letters, digits, spaces, periods, underscores, +and hyphens; at most 32 names are admitted, each at most 120 characters. +Names must identify analyzers registered for the selected program. Unknown names +or options that remain enabled abort the headless import before auto-analysis +and the bridge, so an unsuccessful override cannot produce a session claiming +that the analyzer was disabled. For Windows PE resource analysis, the exact name +is `WindowsResourceReference`. Disabling an analyzer skips the facts it would +have produced. + +### Ghidra heap and CPU controls + +Set resource controls in the environment that launches the CLI or MCP server, +before opening a new Ghidra session. On Linux and macOS, REA chooses the first +nonempty setting in this order: `GHIDRA_HEADLESS_MAXMEM`, `GHIDRA_MAXMEM`, then +`2G`. The chosen value becomes the JVM's `-Xmx` argument. Use a JVM heap-size +value such as `512M` or `2G`; an invalid value causes Java startup to fail. +The supported Ghidra 12.1.4 Windows headless script consumes the same settings +with the same precedence. + +For a small target on a constrained host: + +```bash +export GHIDRA_HEADLESS_MAXMEM=512M +``` + +In PowerShell: + +```powershell +$env:GHIDRA_HEADLESS_MAXMEM = "512M" +``` + +An MCP client must pass this setting to its REA server process; changing an +unrelated terminal's environment does not reconfigure an existing server or +JVM. A 512 MiB heap was verified with small native fixtures, but larger targets +can require more memory. The Java heap limit does not bound JVM RSS, Node's +heap, or total memory used by the process family. The startup deadline controls +waiting time independently of these memory settings. + +REA clears `_JAVA_OPTIONS`, `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`, and +`GHIDRA_JAVA_OPTIONS` inherited from the caller, and owns +`GHIDRA_HEADLESS_JAVA_OPTIONS`. Custom flags injected through these variables +are not supported configuration. On Windows, REA replaces `JDK_JAVA_OPTIONS` +with its own isolated home/temp settings and `-XX:-UsePerfData`; on Linux and +macOS it supplies isolated paths directly to Java. Use the supported heap +settings above instead of adding a second `-Xmx` through an injection variable. + +The Linux/macOS launch sets `-XX:ParallelGCThreads=2` and +`-XX:CICompilerCount=2`; the supported Windows headless script also sets these +counts. These constrain particular JVM thread pools, not all analysis threads +or CPU usage. REA does not pass Ghidra's `-max-cpu` option or expose a general +Ghidra CPU limit. When needed, apply host CPU affinity and scheduling controls +to the REA process and verify the resulting JVM's affinity. Select CPUs allowed +on the host; do not assume CPU numbers from another machine are valid. + +Verify controls at their consumer after the first Ghidra-backed query starts +the JVM: inspect that owned JVM's effective `-Xmx` and GC/compiler flags, CPU +affinity, and observed memory use. Do not infer them from the parent shell's +environment or the absence of an error. On Linux, `/proc//cmdline` +contains the launch arguments and `/proc//status` reports +`Cpus_allowed_list` and `VmRSS`. Inspect only the process belonging to this +session and retain the resource flags needed for the measurement rather than +copying full command lines or environments into reports. Heap and affinity +settings affect cost and latency; they are not part of REA's semantic analysis +profile identity. See [real-provider testing](testing.md) for bounded +verification workflows. + +### Ghidra diagnostics and verification + +Unexpected request failures retain their original internal cause. CLI and MCP +errors expose Error names, messages, and available codes under +`details.diagnostics.failure_cause`, including bounded nested causes and explicit +truncation markers. Darwin ownership-helper compilation failures also retain +the compiler outcome, exit code or signal, and bounded stderr; a timed-out +compiler remains distinguishable from a compiler that exited with an error. +The helper compile deadline defaults to 120,000 ms; set +`REA_SWIFTC_COMPILE_TIMEOUT_MS` to an integer between 1 and 2,147,483,647 when +a busy host needs longer. +Other rejection values retain their primitive value or an explicit type. +Shutdown warnings include the failure +kind, message, and diagnostics, while process and temporary-project cleanup +continues. These messages redact known bridge authentication tokens and +preserve local paths and other analysis context. + +Run `GHIDRA_INSTALL_DIR=... npm run verify:ghidra` from a source checkout to +compile and analyze debug and stripped host-native fixtures (ELF on Linux x64/arm64 +or Mach-O on macOS), plus a native DWARF 4 type-layout object. This lane needs a +host C compiler in addition to Ghidra and its JDK. + +Run `GHIDRA_INSTALL_DIR=... npm run verify:ghidra:cross-format` to add AArch64 +ELF, x86-64 PE, and x86-64 Mach-O fixture coverage. This separate lane needs +`clang`, LLD, and `lld-link` on `PATH`; `REA_CLANG` and `REA_LLD_LINK` select +alternate command paths. Missing cross-target tooling does not block the +host-native Ghidra acceptance lane. + +On a controlled Windows x64 runner, use +`npm run verify:ghidra:windows`. The verifier generates a deterministic native +PE fixture from source bytes and requires the Windows native authority before +opening the provider. The controls are implemented on main; see the +[release boundary](#released-package-and-main). The lane verifies all 26 admitted +read-only operations, digest identity, and runtime cleanup. The separate +`verify:ghidra:windows:package` lane checks the packed CLI/MCP boundary with an +ordinary user. It requires the built Windows native bundle and an existing +Ghidra/JDK installation; neither is inferred from startup alone. + +## MCP Registry + +REA is published in the official MCP Registry as `io.github.morluto/rea`. Registry +clients can discover the server and install the existing public `rea-agents` npm +package; the Registry entry does not introduce a second distribution artifact. + +For a client that supports Registry discovery, search for `io.github.morluto/rea` +and select the npm package. The published metadata launches the existing stdio +server through `npx` with the `mcp` command. + +For a client that requires manual configuration, use: + + + +```json +{ + "mcpServers": { + "rea": { + "command": "npx", + "args": ["-y", "rea-agents@6.5.0", "mcp"] + } + } +} +``` + + + +Persistent registrations should use one exact package version. `rea setup` +writes the same package-runner shape, or `bunx rea-agents@ mcp` when +setup runs through `bunx`, and pins it to the exact version that performed +setup. Run current setup to refresh an older registration, then restart the +client. + +## Package runners and global installation + +A package-runner invocation can use a REA version installed in the current project. To +request the latest release explicitly, use: + +```bash +npx rea-agents@latest setup +``` + +REA runs the version npm selects. To update older agent registrations, run the +latest-version command and review its setup plan. For unattended package +downloads, add `--yes` before the package name; this does not approve REA's +setup changes. + +For an intentional rollback, make the package request explicit: + +```bash +npm exec --yes --package=rea-agents@2.4.0 -- rea setup +``` + +Setup continues to pin persistent MCP registrations to the exact version that +performed setup. Running current setup later migrates unversioned or older +managed registrations through the normal reviewed setup transaction. + +With Bun, `bunx rea-agents setup` (or `bunx rea-agents@latest setup`) is the +equivalent entry point. Setup run through `npx` registers +`npx -y rea-agents@ mcp`; setup run through `bunx` or `bun x` registers +`bunx rea-agents@ mcp`. On Windows, setup wraps either command in +`cmd.exe /d /c` so clients can start the runner's command shim. Neither +registration points into the runner's temporary package cache. + +REA supports Node.js 22.x (>=22.19), 24.x (>=24.11), and 26+. Node.js 23, 25, and prereleases are unsupported. It uses the npm already paired with that runtime and never upgrades Node.js, npm, or Homebrew. + +When REA runs on Bun, the `rea doctor` `node` check reports the Bun version and +the Node.js compatibility version Bun declares, and passes when that +compatibility version is in the supported range. Bun does not enforce the V8 +heap flags REA gives its owned helper processes, so Evidence that reports those +limits on Node.js records them as unavailable under Bun. On Windows, the owned +Job Object of each JavaScript helper (source analyzer, source-map codec and HAR +decoder) instead limits its committed memory to that helper's heap budget plus +a 512 MiB reserve for Bun itself, and Evidence reports that limit. This needs +the matching bundled Windows native artifact; an artifact without the control +refuses to start the helper rather than running it unlimited. CI tests Node.js +only. + +Running `npm install rea-agents` without `--global` installs the executable only +in the current project's `node_modules/.bin`; it does not make `rea` available +on the shell `PATH`. Use the setup command above for the guided setup +journey, `npx -y rea-agents@latest` for unattended one-off commands, or install globally +with `npm install --global rea-agents` for a shell-visible `rea` command. + +The optional curl wrapper installs only the global npm package: + +```bash +curl -fsSL https://raw.githubusercontent.com/morluto/rea/main/install.sh | bash +``` + +It prints the version, runtime, npm command, and destination before installing. When a controlling terminal exists it starts `rea setup`; otherwise it prints the command to run later. + +Pass options with `bash -s --`: + +```bash +curl -fsSL https://raw.githubusercontent.com/morluto/rea/main/install.sh | + bash -s -- --dry-run +``` + +Supported options are `--version `, `--dry-run`, `--no-setup`, `--no-prompt`, and `--verbose`. Neither `--no-prompt` nor a non-interactive shell grants permission to install external dependencies. diff --git a/docs/live-view-reimplementation.md b/docs/live-view-reimplementation.md new file mode 100644 index 0000000..9fcefc6 --- /dev/null +++ b/docs/live-view-reimplementation.md @@ -0,0 +1,187 @@ +# Live View and Recording Reimplementation Research + +Date: 2026-10-16 + +## Goal + +Assess a managed C# replacement for the minimum useful Surveillance Client workflows: persisted server credentials, one or more live camera views, and arbitrary recording-range downloads to MP4. Target .NET 10 and Avalonia for a possible Windows/macOS/Linux UI, and prefer FFmpeg for media decode, mux, and encode rather than the legacy playback DLL. + +## Current Findings + +### Native network API candidate + +`RSNet.dll` is a native x86 PE library. REA's procedure-name search found an application-facing API surface that includes: + +- Lifecycle and connection: `RSNetInit`, `RSNetRelease`, `RSNetConnectionStart`, `RSNetConnectionStartEx`, `RSNetConnectionStop`. +- Discovery and device configuration: `RSNetSearchDev`, `RSNetSetDevInfo`, `RSNetSetNewDevInfo`, `RSNetGetDevInfo`, `RSNetGetDevInfoEx`, `RSNetSetIPAndPort`. +- Live view: `RSNetStartPreview`, `RSNetStopPreview`, `RSNetGetPreviewBitRate`, `RSNetForceIFrame`. +- Recording search and retrieval: `RSNetQueryRecord`, async/Ex variants, `RSNetStartDownloadRecord` and `RSNetStartDownloadRecordEx`, record-playback controls, and `RSNetConnectionStop`. +- Additional functions include PTZ, audio talk, parameter queries, alarms, logs, upgrade, snapshot, and picture-download operations. + +This is strong evidence that the installed network DLL contains useful operations for the requested feature set, but it is not yet a usable C# contract. Ghidra identifies the library as x86 and reports `RSNetConnectionStartEx` as `__stdcall` with an opaque integer argument and pointer-like return. The record-download Ex entry takes opaque pointer arguments. Its analyzed setup path allocates buffers, copies arrays with element sizes `0x1c` and `0x108`, then queues work with `QueueUserWorkItem`; the exact request structures, callback/event contract, ownership, and cancellation rules remain unresolved. + +### Initial reuse recommendation + +For a temporary Windows compatibility prototype, the x86 DLLs could live in a supervised x86 worker. For the requested managed multiplatform product, treat that only as a behavior oracle during reverse engineering, not as the final architecture. Keep protocol and media code managed/platform-neutral, and abstract credential storage behind per-OS secure stores; do not persist credentials in plaintext. + +The presence of record query/download functions does not establish that the DLL emits a standard container or MP4. MP4 output should be treated as a separate remux/transcode stage until the downloaded bytes and codec/container contract are verified. + +### Playback and MP4 boundary + +`RSPlay.dll` is also x86. Its named procedure inventory includes play-instance create/destroy, window binding, `RSPlayInputNetFrame`, draw/decode callback registration, playback controls, and `RSPlay264ToAviStart/Stop`. The frame-input wrapper dispatches through an opaque instance vtable; the AVI conversion entry is another vtable dispatch and shares an address/name with `RSPlayConvertFileStart`. This is evidence of a native decode/render path and an AVI conversion path, not a documented managed ABI or proof of MP4 support. No MP4-named procedure appeared in the complete provider-defined procedure-name search for `RSPlay.dll`. + +The bundled `hi_h264dec_w.dll` is x86 and exposes `Hi264DecCreate` and `Hi264DecFrame` names. Ghidra infers that creation accepts a pointer to an undocumented configuration structure and returns an opaque handle; the frame routine accepts seven low-level parameters. Avoid binding this decoder directly unless the SDK wrapper proves unusable. + +For MP4, first capture the exact downloaded payload and inspect its codec, framing, timestamps, and audio. Then use a maintained FFmpeg-based remux when the source streams are compatible with MP4; transcode only when required. The legacy AVI conversion can be a compatibility fallback, not the preferred output path. Container behavior and whether arbitrary subranges can be cut without keyframe expansion remain runtime questions. + +### P2P and initialization boundary + +`RSNetInit` clears global state, derives the directory of the calling process, appends `\\RSNet.ini`, parses that file, and initializes Winsock 2.2. `RSNetInitLX2PPath` copies a caller-supplied path into global storage. The `RSNet.dll` string inventory includes `RSP2PClient.exe`, `RSP2PDaemon.exe`, and P2P/relay labels. These are static references; they do not prove which helper is launched or under what conditions. + +The installation contains several vendor-specific P2P directories. The inspected `p2p/SY/PPCS_API.dll` has named initialize/connect/read/write/close/status procedures, but its connect entry aliases shared native code and the exact public parameter contract was not recovered. This makes it a potential provider-specific fallback, not a universal DVR transport. Prefer routing through `RSNet` unless testing establishes that direct use of a particular provider is necessary and supported. + +### Main executable coverage + +REA opened `Surveillance_client.exe` as an x86 PE with SHA-256 `dc6050f9c96fa68270b79b17d9c2127f0de4f3ddd3478a1c0c552134fff7de14`. The PE resource parser completed and identified a PE32 image. Ghidra's broad overview and focused procedure/string searches on this 10.8 MB executable timed out, including a sequential retry; therefore this pass does not establish the EXE's exact call sequence into `RSNet`/`RSPlay` or the import table. Existing DPI findings are recorded separately in [surveillance-client-dpi-analysis.md](surveillance-client-dpi-analysis.md): Qt 4-era widgets, no obvious static DPI-awareness logic, and persisted pixel geometry. A fresh managed UI should address DPI independently of the native worker. + +## Managed Reimplementation Effort + +### Bottom line + +A .NET 10/Avalonia application is technically viable: Avalonia's upstream build currently targets `net10.0` across its desktop code ([target framework configuration](https://github.com/AvaloniaUI/Avalonia/blob/master/build/TargetFrameworks.props)). That establishes UI framework compatibility, not portability of this DVR's network protocol or the FFmpeg native binaries. FFmpeg can replace much of `RSPlay`'s decode/render and AVI conversion work; it cannot replace `RSNet`'s authentication, command protocol, recording index, or vendor P2P behavior. + +The hardest work is discovering and reproducing the wire protocol and any P2P transport, not building the Avalonia screens or calling FFmpeg. REA found `RSNet` entry points that mostly forward opaque structures into internal stateful code. A record query snapshots session data, increments a shared request ID, coordinates through Windows event/critical-section machinery, and waits for a response with a 20-second timeout. The download path additionally allocates/copies native record arrays and queues asynchronous work. These behaviors need a managed protocol/state-machine design, not mechanical translation of export names. + +### Planning estimate + +Estimates are engineer-weeks for one experienced engineer, assuming access to a representative DVR and firmware. They are deliberately conditional: one successful original-client login and a bounded header-only capture are now observed, but managed-client authentication, live preview, recording, and the main executable's broad Ghidra analysis remain unverified. + +| Scope | Effort | Assumptions | +|---|---:|---| +| Go/no-go discovery spike | 2-4 weeks | One device/firmware; establish credentials/auth, direct-LAN connection, one decodable live stream, record search, and a short export. | +| Limited MVP after a successful spike | 12-20 additional weeks | One device family, direct IP/TCP without vendor P2P, a standard H.264/H.265 plus optional AAC stream, agreed camera-count target, arbitrary range search/download, and MP4 output. | +| Add one P2P provider | 4-12+ additional weeks | Provider-specific protocol and relay behavior can be observed; vendor servers and credentials remain accessible. Could be blocked without a documented or observable protocol. | +| Reproduce broad RSNet/RSPlay feature parity | 24-52+ weeks | Includes non-requested surfaces such as PTZ, audio talk, alarms, parameter/config operations, upgrades, fisheye and legacy playback behaviors; excludes extensive multi-family certification. | + +The spike plus limited MVP is roughly 14-24 engineer-weeks, or about 3.5-6 months for one full-time engineer. Allow at least +/-50% until a real connection and stream capture prove the framing, authentication, and time-range semantics. Each additional device/P2P family expands both implementation and certification; it is not safe to assume the named P2P DLLs share one protocol. + +### What FFmpeg removes, and what it does not + +- `RSPlay`'s H.264/H.265 decoding, frame conversion, audio decode, and AVI conversion can likely be replaced with FFmpeg plus Avalonia frame presentation. The RSNet-to-media packet framing, decryption, timestamps, and channel metadata still need to be understood before FFmpeg can consume the stream. +- Prefer stream-copy/remux for MP4 when downloaded packets use an MP4-compatible codec and carry usable timestamps. Transcode only when framing, codec, or timestamp constraints require it. Arbitrary range boundaries may need to expand to keyframes and then be trimmed/re-encoded for exact boundaries. +- Start with FFmpegCore, which drives the native FFmpeg executable through a C# process wrapper. Feed live media over redirected stdin/stdout pipes and use the same backend for MP4 exports; codec work still runs in native FFmpeg. The process boundary is not automatically a performance problem, but live latency, buffering, and extra copies must be measured. +- Keep FFmpegCore behind app-owned media interfaces so a later FFmpeg.AutoGen backend can call `libav*` in-process without changing protocol, view-model, or Avalonia code. Do not expose FFmpegCore command builders, process types, or FFmpeg native pointers outside the backend adapter. +- Model the adapter boundary around encoded packets and decoded frames: packets carry codec/stream metadata, owned payload bytes, PTS/DTS, time base, and keyframe flags; decoded frames carry dimensions, pixel format, and owned pixel memory. Live decode and MP4 mux/remux can be separate interfaces. This keeps packet parsing in the protocol layer and rendering in Avalonia. +- If FFmpegCore's pipe latency/copy cost is unacceptable, replace only the media adapter with FFmpeg.AutoGen. Benchmark with the target camera count and resolution before switching; in-process calls reduce process/pipe overhead but do not make the native codec work itself faster. +- Both approaches require compatible native FFmpeg builds for each RID and review of LGPL/GPL configuration and codec licensing. +- FFmpeg does not implement DVR login, command messages, record search, P2P rendezvous/NAT traversal, or proprietary encryption. Those are the dominant unknowns for a true managed RSNet replacement. + +## Proposed .NET/Avalonia Shape + +1. Use an Avalonia desktop app targeting `net10.0`, with protocol, device models, and recording logic in separate platform-neutral .NET libraries. +2. Define provider interfaces for direct TCP and each vendor P2P family; start with one direct-IP provider. Keep auth/session lifecycle, heartbeat, retry, cancellation, and protocol parsing independent from Avalonia. +3. Start with FFmpegCore behind app-owned `ILiveVideoDecoder` and `IRecordingMuxer`-style contracts. Keep the contracts independent of FFmpegCore and Avalonia; pass timestamped encoded packets in and owned decoded frames out. Feed FFmpeg only after DVR framing and timestamps are understood, and render frames in Avalonia without legacy Qt/Win32 window handles. +4. Define an `ICredentialStore` abstraction with Windows Credential Manager/DPAPI, macOS Keychain, and Linux Secret Service implementations. Avalonia itself does not make secret storage portable. +5. Keep the original x86 DLLs only as an optional Windows-side comparison oracle during development, subject to runtime access and redistribution terms. Do not make the final cross-platform app depend on them. +6. Validate one camera and one recorded range first; then test concurrent feeds, time zones/DST, keyframe boundaries, cancellation, reconnects, audio, and exported MP4s on each supported OS. Keep a fake media-adapter test and packet fixtures so FFmpegCore and a future FFmpeg.AutoGen implementation can be compared against the same contract. + +Before redistribution, verify the vendor DLLs and P2P SDK licensing, supported Windows versions, and all native runtime dependencies. Their presence in the installation does not grant redistribution rights or establish ongoing security maintenance. + +## MVP Technical Specification + +### Project and dependency layout + +Use separate class libraries for application logic, protocol contracts, the RSNet implementation, media contracts, and infrastructure adapters. The Avalonia executable is the composition root and references the concrete adapters; application and domain code do not reference Avalonia, FFmpegCore, or native vendor DLLs. + +| Project | Responsibility | Project references | +|---|---|---| +| `Surveillance.Client.Domain` | Device endpoints, channel identity, connection/preview state, and domain errors. No UI or vendor types. | None | +| `Surveillance.Client.Protocol.Abstractions` | `IDeviceSessionFactory`, `IDeviceSession`, and preview-stream contracts, including typed login outcomes. | `Surveillance.Client.Domain` | +| `Surveillance.Client.Media.Abstractions` | Owned encoded-packet and decoded-frame DTOs; `ILiveVideoDecoder` and future `IRecordingMuxer` contracts. | None | +| `Surveillance.Client.Application` | Connect/authenticate, start/stop preview, and credential workflows. Defines the `ICredentialStore` port and coordinates protocol/media abstractions. | Domain, Protocol.Abstractions, Media.Abstractions | +| `Surveillance.Protocol.RSNet` | Managed direct-IP transport, framing, authentication, preview parsing, timeouts, and cancellation for one verified device family. | Domain, Protocol.Abstractions | +| `Surveillance.Media.FFmpegCore` | FFmpegCore process/pipe adapter implementing the app-owned media contracts. No FFmpegCore types escape this project. | Media.Abstractions | +| `Surveillance.Infrastructure.Credentials` | OS-backed secure credential-store adapters. | Application | +| `Surveillance.Client.App` | Avalonia Views and ViewModels, UI dispatch/frame presentation, logging, and DI composition root. | Application, Protocol.RSNet, Media.FFmpegCore, Infrastructure.Credentials | + +Keep each later P2P implementation in its own provider project implementing `Protocol.Abstractions`; do not add P2P to the direct-IP MVP. Test projects reference only the layer they exercise: `Surveillance.Client.Domain.Tests`, `Surveillance.Client.Application.Tests`, `Surveillance.Protocol.RSNet.Tests`, `Surveillance.Media.FFmpegCore.Tests`, and `Surveillance.Client.App.Tests`. + +### MVVM and dependency injection + +- Use CommunityToolkit.Mvvm for observable ViewModels and commands. Views bind to ViewModel properties/commands; ViewModels do not call sockets, FFmpeg, credential APIs, or RSNet exports directly. +- Build the service provider in `Surveillance.Client.App` during Avalonia startup, using `Microsoft.Extensions.DependencyInjection` (and the Generic Host if host-managed logging/configuration is useful). Register application use cases and ports, then their concrete adapters. Resolve top-level windows through the composition root; use constructor injection below it, not a service locator. +- Keep a `DeviceConnectionViewModel` responsible for endpoint fields, saved-device selection, and connect errors. A `LiveViewViewModel` owns the selected channel and start/stop command state. Inject use-case services into both; no ViewModel owns a protocol handle or FFmpeg process. +- Keep Avalonia dispatcher and bitmap conversion in the presentation project. Application services publish app-owned frames; the presentation adapter marshals updates onto the UI thread and writes into a stable-size Avalonia image surface. +- Store the endpoint and username as device configuration and the password/token in an OS secure store behind `ICredentialStore`. Do not log credentials or include them in exception messages. Windows Credential Manager/DPAPI, macOS Keychain, and Linux Secret Service are implementation choices behind that port, not dependencies of the application layer. + +### Auth-to-single-live-feed vertical slice + +The first end-to-end slice is one direct-IP device, one selected channel, and live video only. Recording search/download, P2P, audio, PTZ, and multi-camera layouts remain later increments. + +1. The user selects or enters a device endpoint and credentials. +2. The application saves secrets through `ICredentialStore` after successful authentication. Remembering is enabled by default and can be disabled; on reconnect saved values fill blank credential fields. +3. `ConnectDevice` opens a TCP session through `IDeviceSessionFactory` and sends the mode-0 login request. `FUN_100090e0` selects command `0x1f` with a 16-byte little-endian header and an `0x50`-byte payload: two 36-byte NUL-terminated narrow-string fields followed by two option dwords. Runtime capture of a successful original-client login confirmed `RSNetConnectionStartEx` mode 0 and the transformed-header flag `0x02`. The native worker applies its bit permutation to header bytes `2..15` and the full request payload; it reverses the permutation on the response header and response payload. The managed client now implements this mode-0 transform. Response status is at header offset `+2`; status zero is accepted only when the decoded response body has an `RS` marker at offset `+6`. The native receive helper places the response body at `16 + ((flags >> 2) * 4)`, so the managed reader skips any indicated extension words. The original-client UI reached its logged-in view; managed hardware authentication remains to be retested. The managed implementation uses UTF-8 for the native narrow-string fields, zeroes the uncharacterized option dwords, and leaves nonzero status codes unmapped; encoding, option values, and nonzero status meanings still need device validation. Alternate commands `0x269`/`0x26b` are not implemented. Credentials are sent in cleartext over TCP; use only on a trusted network or VPN until the transport is validated. Connection and authentication diagnostics are written by NLog under the platform's LocalApplicationData `SurveillanceClient/logs` directory, one file per day; credential values and packet payloads are not logged. +4. After authenticated state, `StartLivePreview` requests one channel from `IDeviceSession` and returns an owned async packet stream. The RSNet adapter must first establish the actual preview packet callback/source, framing, codec metadata, timestamps, and buffer ownership. Parse vendor framing in the protocol project; pass only verified elementary-stream access units to media code. +4. `ILiveVideoDecoder` consumes `EncodedVideoPacket` values and yields `DecodedVideoFrame` values. Packets carry codec/stream metadata, owned bytes, PTS/DTS, time base, and keyframe status. Frames carry dimensions, pixel format, row stride, and memory with explicit ownership/lifetime. Keep queues bounded and measure the backpressure policy; never queue unbounded frames on the UI thread. +5. The Avalonia presentation adapter converts frames to its image surface and dispatches updates to the UI thread. Neither protocol DTOs nor media contracts contain Avalonia or FFmpegCore types. +6. Stop is idempotent and cancellation-aware: cancel packet consumption, stop the preview, dispose decoder resources, then disconnect and dispose the device session. Clear displayed frame state and surface terminal errors without exposing secrets. Preserve this order even when preview startup or decoding fails partway through. + +**Discovery gate before claiming hardware compatibility:** use a controlled session with one identified device model/firmware to confirm (a) managed authentication against the device, credential encoding, option fields, nonzero status mapping, and cleartext/TLS behavior, and (b) the preview-start handoff and encoded packet boundaries/timestamps. The original client has now authenticated successfully in the UI; a Frida capture observed mode 0, the 96-byte login send, and response traffic while reading no credential payload bytes. Produce sanitized deterministic fixtures and verify direct-IP behavior. The managed implementation is informed by that trace and local fake-server tests, but has not yet passed a hardware login. The UI can report authenticated state while preview remains explicitly unavailable. + +### Test plan and acceptance + +| Test project / level | Required coverage | +|---|---| +| `Surveillance.Client.Domain.Tests` | Valid/invalid session-state transitions; channel and endpoint invariants; error classification. | +| `Surveillance.Client.Application.Tests` | Connect/auth/start/stop orchestration with fake protocol, credential, and decoder ports; wrong credentials, timeout, cancellation, partial-start failure, and repeated stop; assert secrets never appear in logs. | +| `Surveillance.Protocol.RSNet.Tests` | Captured native mode-0 header golden vector, transformed login request/response loopback coverage, and status rejection; managed hardware auth, preview parsing, fragmentation/coalescing, timeout, and cancellation remain gated on runtime evidence. | +| `Surveillance.Media.FFmpegCore.Tests` | FFmpeg argument construction, pipe input/output, bounded stderr handling, process exit/error mapping, cancellation, and process cleanup. Use a small known media fixture for adapter integration; keep process invocation behind a narrow test seam if needed. | +| `Surveillance.Client.App.Tests` | ViewModel command/state/error behavior with fake use cases and frame presenters; no DVR or FFmpeg executable required. | +| Opt-in hardware integration | One supported model/firmware over direct IP: correct and incorrect login, one channel start, continuous decode, stop/restart, disconnect, and reconnect. Keep this separate from ordinary CI and sanitize any captured fixtures. | + +The MVP is accepted when credentials survive app restart only through the OS secure store; one verified direct-IP login produces an authenticated state; one channel displays decoded frames for a 30-minute soak without unbounded queue growth; login/transport/decode failures are visible and recoverable; and stop/cancellation leaves no preview session, socket, or FFmpeg process behind. Record the tested model, firmware, OS, codec, latency, and reconnect behavior. These criteria are conditional on passing the discovery gate and do not imply broad device-family support. + +## Evidence Ledger + +Evidence below combines static analysis of the installed artifacts with bounded original-client runtime login captures. Credential fields were never read; follow-up captures sampled only the two mode-0 option dwords and decoded response bytes 6–7. The UI success result was user-reported. + +| Evidence | Observation | Boundary | +| Original-client response marker (2026-10-16) | The native decoder returned a 1,232-byte body with bytes `53 52` at offsets 6-7; the native worker compares these as little-endian `0x5253`. A separate request capture observed zero-valued option dwords at payload offsets 72 and 76. | Only the two marker bytes and two non-credential option dwords were read; credential fields and all other payload bytes were not accessed. | +|---|---|---| +| Original-client Frida login capture (2026-10-16) | The x86 client called `RSNetConnectionStartEx` with mode bytes `0x35=0` and `0x36=0`, connected to `192.168.100.92:9000`, sent 96-byte login frames with transformed-header flag `0x02`, and received response traffic. The user confirmed the UI reached its logged-in view. | Captured only mode bytes, the first 16 bytes of 96-byte sends, response headers, socket results, and byte counts; request/response payload bytes were never read. UI outcome is user-reported. | +| `ev_0d183bb60c1fc079d8b16095cd7e6e0a89d4915bce519bcfb7327dabd7bc4ebd` (`search_procedures`, Ghidra 12.1.4) | `RSNet.dll` contains named connection, preview, record-query, record-play, and record-download procedures; Winsock imports include `connect`, `send`, and `recv`. | Procedure-name search over the provider's defined procedure inventory; names alone do not establish semantics or export ABI. | +| `ev_d42fbe012e26d4981a08e00ce46e70433e362db4ec26a3f14c685fe3a9e3bb00` (`analyze_function`, `RSNetConnectionStartEx`) | Ghidra reports an x86 `__stdcall` wrapper returning an opaque pointer and accepting one integer-like argument. | Decompiler-derived signature and body for this function; types are inferred from machine code, not vendor headers. | +| `ev_6c73effc02cb39d7d7b41c1d20d3d7b727c24848d206658e748862c0df8efb49` (`analyze_function`, `RSNetStartDownloadRecordEx`) | The wrapper accepts two opaque pointer-like arguments and delegates into native request setup. | Decompiled wrapper; the vendor request type and completion contract are unresolved. | +| `ev_1b112461309bd2e0f9d5d88f747eaf58bd118717148ca9f28e93fc37b9803db6` (`analyze_function`, `FUN_100056c0`) | Preview setup uses a critical section and searches/updates a native collection of session-like objects. | Decompiled function body; names and business meaning of fields are unknown. | +| `ev_e2f17ef25e28e6555e8f96d89b6fcf19d7bccdde1778533bf9dd46635ce2f3ad` (`analyze_function`, `FUN_100103b0`) | Record-download setup allocates/copies per-item buffers and submits a worker through `QueueUserWorkItem`. | Decompiled setup body; queued callback was not recovered as an independent procedure, so transfer and completion semantics remain open. | +| `ev_dc360c49f596100f1bf3d0a2a6df8978f3417a44a185b8a83fe980aa1f400565` (`analyze_function`, `RSNetConnectionStart`) | The public start entry allocates a `0xe98`-byte native object, initializes it through internal helpers, and returns an opaque pointer on success. | Decompiled wrapper; the object layout and actual login/session protocol remain unresolved. | +| `ev_99413f5c1c8b3db71a1b27f2b9859cfd6b9610b855f79975ba8ef145a8b50166` + `ev_04e06a1dfc520df682f516a62663b9ad28a0b825f2e2d3000897afcd80cdc8c0` + `ev_0cd45ef8fd8357e2c1afc1ade8845694727737f2c94e06ed4031810f88340ade` (`analyze_function` / referenced-strings view / xrefs, `FUN_100090e0`) | The x86 worker constructs default login command `0x1f`, a 16-byte header, and an `0x50`-byte payload. It copies two NUL-terminated strings into 36-byte fields, appends two option dwords, applies the native bit permutation for transformed mode, and validates a successful response with an `RS` marker. | Static worker analysis plus the mode-0 runtime capture above. Native narrow-string encoding, option-dword meanings/defaults, and managed-device acceptance remain unverified. | +| `ev_0316a50fa696dd6bbd9f4b84d255689bf6e731b61ec87213da4f80ba188d8393` (`procedure_pseudo_code`, `FUN_100205f0`) | The native helper concatenates a 16-byte header and payload, then calls TCP `send` once and requires the complete byte count. | Assembly/pseudocode of the shipped x86 DLL; it does not establish server acceptance or retry behavior. | +| `ev_66deb589c677f148df9dfede536881c7a90b2a3288901b1c09413e57649740bc` + `ev_6185a26b99ab42e3cfb3b79dc33c3e6b9decb86cf85478ed9777ca6ce6fd62aa` + `ev_6039a85e773b6e22118b90146d6c46fb91ce0c94d4cf64da303235bec0fbed6a` (`procedure_pseudo_code`, receive/header helpers) | The worker reads and reverses the transform on the response header; status is at offset `+2`, zero is success, and `FUN_10003d30` computes the body offset as `16 + ((flags >> 2) * 4)`. It also reverses the response-payload transform before checking `RS` at body offset `+6`; statuses `0x32`/`0x33` set native last-error values. | Static pseudocode plus one successful original-client UI result. Other modes and nonzero status meanings remain unresolved. | +| `ev_34b043c2cfc9f58d0f6ae6798e5531cc4ba34d7b85ab09f9888409b4beefebbe` (`analyze_function`, `RSNetStopPreview`) | The wrapper checks the context and preview handle, calls an internal stop helper, and clears the caller's handle. | Decompiled wrapper at `0x1001c4b0`; helper behavior and packet callback ownership remain unresolved. | +| `ev_c4d3300ea096044c2059e299fae4fd0e864ca62750f5953093405d5e73646a40` (`analyze_function`, `RSNetConnectionStop`) | The wrapper clears the caller's connection pointer and invokes internal shutdown/cleanup helpers for the opaque object. | Decompiled wrapper at `0x1001d0a0`; exact socket/thread shutdown ordering is not established by this wrapper alone. | +| `ev_79ede58629e436b4f454692234adec46614109fb731e7852fcf0454b17a10a4d` (`analyze_function`, `RSNetStartPreview`) | The named start wrapper accepts opaque arguments and delegates preview creation into native state. | It does not establish encoded packet format or the callback/handoff consumed by the original client. | +| `ev_71287e7cb6a061428ece1415f8bf430a5e489914d808cf3f9c37a27bbfa0172a` (`analyze_function`, `RSNetSetDevInfo`) | The function copies `0x48` bytes from its argument and submits a request through internal command machinery. | Structure fields and request purpose are unknown; this is not evidence that the call authenticates a user. | +| `ev_50ae9861dde2005e0a53bc34848c6fefa540a43cf02679531ffd6adfb208a3bf` (`analyze_function`, `RSNetQueryRecordEx`) | Record-query Ex is a short `__stdcall` wrapper taking two opaque pointers and calling an internal query routine. | Does not reveal the public request structure or returned record layout. | +| `ev_5efc588c56e04dc41e8c404e5cb2b74f67afc1e2e2828156e28403421e0bd18b` (`analyze_function`, `FUN_10005eb0`) | The internal record-query path snapshots native state, increments a shared ID, builds request data, and calls a helper with a 20,000 ms timeout. | Decompiled helper; protocol fields and response-to-record mapping are not fully recovered. | +| `ev_f0544388b10f903585f5a108d435109deffec0bda80822656f032d88dd2dd1f6` (`analyze_function`, `FUN_10007330`) | The shared operation queues work under a critical section and waits on a Windows event before returning completion state. | Decompiled synchronization path; it does not by itself identify all socket framing or error semantics. | +| `ev_f42bdfeee987ace213d45429f70c1b137c00fabda859cf6c109536402da45ad4` (`analyze_function`, `RSNetInit`) | Initialization derives the process directory, reads adjacent `RSNet.ini`, and configures Winsock 2.2. | Ghidra pseudocode; configuration parser semantics and runtime side effects remain untested. | +| `ev_de6bc45e95104efae090a5cc3bfac1b363e8e088b69ca529ad086e044e8c6f44` (`analyze_function`, `RSNetInitLX2PPath`) | The function copies a caller-provided path into global storage. | Decompiled function; the code selecting the path and loading any provider was not established. | +| `ev_e973cdc2def91d1adf12ca6361e11f311226f31df289e35bbe1c7646da1c6f6d` (`search_strings`, `RSNet.dll`) | Defined strings include `RSP2PClient.exe`, `RSP2PDaemon.exe`, and P2P/relay labels. | String inventory observations; do not prove process creation or actual provider selection. | +| `ev_a8fff3b40ce4ff520544fe21413db41a358162f4e119b9b11f7a7c36dd3e2769` (`search_procedures`, `RSPlay.dll`) | Named procedures include per-instance playback, network-frame input, decode/draw callbacks, and H.264-to-AVI conversion. | Complete matching defined procedure-name inventory; names do not establish a stable ABI or runtime support. | +| `ev_652be99a1040641c0e78b429cb0dd33846a83c41ab93ef894df5bbd266e7c3df` (`analyze_function`, `RSPlayInputNetFrame`) | The wrapper takes an opaque instance plus two untyped frame parameters and dispatches through a vtable. | Ghidra decompiler signature and body; frame format and ownership remain unknown. | +| `ev_5c28c886f02fe1e47c04ab27320b582d1cb97adf64028ae8c3625864a5e1d5af` (`analyze_function`, `RSPlay264ToAviStart`) | The named AVI conversion entry dispatches through an opaque instance vtable. | Does not establish input/output container details or MP4 capability. | +| `ev_45c4ccbaf121078046672af89dbe07be2d5547b5da13d2e758895977f6bf289d` (`analyze_function`, `Hi264DecCreate`) | H.264 decoder creation takes a pointer to an undocumented config structure and returns an opaque handle. | Ghidra-derived signature; config layout and decoder requirements are unknown. | +| `ev_5dd43643df5d5bd620a18f8da397e72be4dc30e3ed684741109cbee957d14866` (`analyze_function`, `Hi264DecFrame`) | H.264 frame decoding has seven low-level parameters and mutates decoder state. | Ghidra-derived signature; exact types and buffer contract are unknown. | +| `ev_df13bfe4608c52a275d7d6fdd87d924dfd2d1027ff465227fd6837bd35d786c9` (`search_procedures`, `p2p/SY/PPCS_API.dll`) | The SY P2P library contains initialize/connect/read/write/close and status procedure names. | One vendor-specific library only; the search does not establish device-family compatibility or a documented ABI. | +| `ev_522a24d172a10c66d2552f0567b22af89a1c2099c5861a9183d7ab405e590edc` (`inspect_pe_resources`, main EXE) | Resource inspection completed for the exact PE32 executable identity and file hash above. | Resource tree only; it does not establish code behavior or manifest loading. | + +## Open Questions + +- Do real devices accept the statically recovered default login frame, UTF-8 string encoding, and zero option dwords? What are the meanings of nonzero login statuses and alternate transformed/command modes? +- Where does the original EXE receive encoded preview packets from `RSNet`, and what are their framing, codec, timestamp, and ownership rules? +- Which exact `RSNet` structures and callback signatures does the original EXE pass for record search and download? +- Can a controlled run against one representative DVR confirm direct-IP authentication and one decodable channel before committing to the managed protocol implementation? +- Does the original client use `RSPlay.dll`, FFmpeg, or the HiSilicon decoder DLLs for live rendering and recorded playback, and can any of them write a standard MP4? +- Which of the vendor-specific P2P SDKs under `p2p/` is selected for each device family, and can a modern client load only the required provider? +- Can the executable and relevant DLLs be analyzed in one complete REA pass? The first broad queries on the 10.8 MB EXE timed out; the smaller `RSNet.dll` target was analyzable. diff --git a/managed-client/.gitignore b/managed-client/.gitignore new file mode 100644 index 0000000..2051be2 --- /dev/null +++ b/managed-client/.gitignore @@ -0,0 +1,5 @@ +bin/ +obj/ +.vs/ +TestResults/ +/dependencies/ \ No newline at end of file diff --git a/managed-client/Directory.Build.props b/managed-client/Directory.Build.props new file mode 100644 index 0000000..72e2dee --- /dev/null +++ b/managed-client/Directory.Build.props @@ -0,0 +1,11 @@ + + + net10.0 + enable + enable + 14 + x64 + x64 + true + + \ No newline at end of file diff --git a/managed-client/Directory.Packages.props b/managed-client/Directory.Packages.props new file mode 100644 index 0000000..e986694 --- /dev/null +++ b/managed-client/Directory.Packages.props @@ -0,0 +1,15 @@ + + + true + + + + + + + + + + + + \ No newline at end of file diff --git a/managed-client/README.md b/managed-client/README.md new file mode 100644 index 0000000..59a29ec --- /dev/null +++ b/managed-client/README.md @@ -0,0 +1,24 @@ +# Surveillance Client (managed prototype) + +SDK-style .NET 10 solution for a 64-bit Avalonia live-view prototype. + +## Build and test + +From this directory: + +```powershell +dotnet restore Surveillance.Client.slnx +dotnet build Surveillance.Client.slnx -c Release +dotnet test --solution Surveillance.Client.slnx -c Release +dotnet run --project src/Surveillance.Client.App -c Debug +``` + +The shared build properties target `net10.0` and `x64`. The app declares `win-x64`, `linux-x64`, and `osx-x64` runtime identifiers. Files in the ignored `dependencies/` folder are copied to `ffmpeg/` beside the built or published app, and the app uses that folder for FFmpegCore. Replace those files in a published `ffmpeg/` folder to use a different FFmpeg build. The binaries are intentionally not committed. + +Open the repository root in VS Code and press F5 to build and launch the x64 Debug app. + +## Protocol status + +The UI, application coordinator, media contracts, FFmpegCore decoder, and tests are implemented. `Surveillance.Protocol.RSNet` deliberately refuses network connections until the login request and preview packet framing are supported by verified fixtures. This avoids sending guessed credentials or presenting a generic protocol as compatible with the shipped client. The app will display that discovery gate when Connect is used. + +The Windows credential adapter stores secrets in Windows Credential Manager. Other operating systems currently fail closed until their native secure-store adapters are implemented. \ No newline at end of file diff --git a/managed-client/Surveillance.Client.slnx b/managed-client/Surveillance.Client.slnx new file mode 100644 index 0000000..e3d1898 --- /dev/null +++ b/managed-client/Surveillance.Client.slnx @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/managed-client/global.json b/managed-client/global.json new file mode 100644 index 0000000..802ab21 --- /dev/null +++ b/managed-client/global.json @@ -0,0 +1,5 @@ +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +} \ No newline at end of file diff --git a/managed-client/src/Surveillance.Client.App/App.axaml b/managed-client/src/Surveillance.Client.App/App.axaml new file mode 100644 index 0000000..4b25116 --- /dev/null +++ b/managed-client/src/Surveillance.Client.App/App.axaml @@ -0,0 +1,8 @@ + + + + + \ No newline at end of file diff --git a/managed-client/src/Surveillance.Client.App/App.axaml.cs b/managed-client/src/Surveillance.Client.App/App.axaml.cs new file mode 100644 index 0000000..7b3736e --- /dev/null +++ b/managed-client/src/Surveillance.Client.App/App.axaml.cs @@ -0,0 +1,79 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using FFMpegCore; +using Microsoft.Extensions.DependencyInjection; +using NLog; +using NLog.Config; +using NLog.Targets; +using Surveillance.Client.Application; +using Surveillance.Client.Media; +using Surveillance.Client.Protocol; +using Surveillance.Media.FFmpegCore; +using Surveillance.Infrastructure.Credentials; +using Surveillance.Protocol.RSNet; + +namespace Surveillance.Client.App; + +public sealed partial class App : Avalonia.Application +{ + public override void Initialize() => AvaloniaXamlLoader.Load(this); + + public override void OnFrameworkInitializationCompleted() + { + InitializeLogging(); + + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + var ffmpegFolder = Path.Combine(AppContext.BaseDirectory, "ffmpeg"); + if (Directory.Exists(ffmpegFolder)) + { + GlobalFFOptions.Configure(options => options.BinaryFolder = ffmpegFolder); + } + + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + var provider = services.BuildServiceProvider(); + desktop.MainWindow = provider.GetRequiredService(); + desktop.Exit += async (_, _) => + { + try + { + await provider.DisposeAsync(); + } + finally + { + LogManager.Shutdown(); + } + }; + } + + base.OnFrameworkInitializationCompleted(); + } + + private static void InitializeLogging() + { + var logDirectory = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "SurveillanceClient", + "logs"); + Directory.CreateDirectory(logDirectory); + + var fileTarget = new FileTarget("file") + { + FileName = Path.Combine(logDirectory, "surveillance-${shortdate}.log"), + Layout = "${longdate}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}", + CreateDirs = true, + }; + var configuration = new LoggingConfiguration(); + configuration.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget); + LogManager.Configuration = configuration; + LogManager.GetCurrentClassLogger().Info("Application logging initialized at {LogDirectory}", logDirectory); + } +} \ No newline at end of file diff --git a/managed-client/src/Surveillance.Client.App/MainWindow.axaml b/managed-client/src/Surveillance.Client.App/MainWindow.axaml new file mode 100644 index 0000000..5b7f72d --- /dev/null +++ b/managed-client/src/Surveillance.Client.App/MainWindow.axaml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +