Metadata-Version: 2.4
Name: ue-remote-exec
Version: 0.2.0
Summary: Talk to a running Unreal Engine 5 editor over its built-in Python Remote Execution channel — no plugin, no C++, no C#.
Author: rfioly
License: Apache-2.0
Project-URL: Homepage, https://github.com/rfioly/ue-remote-exec
Project-URL: Source, https://github.com/rfioly/ue-remote-exec
Project-URL: Used by, https://github.com/rfioly/ue5-editor-agent
Keywords: unreal,unreal-engine,ue5,remote-execution,automation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# ue-remote-exec

Talk to a running Unreal Engine 5 editor from plain Python, over the editor's
built-in Python Remote Execution channel. **No C++ plugin, no project changes, no
editor restart beyond enabling the built-in switch.**

[![CI](https://github.com/rfioly/ue-remote-exec/actions/workflows/ci.yml/badge.svg)](https://github.com/rfioly/ue-remote-exec/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/ue-remote-exec.svg)](https://pypi.org/project/ue-remote-exec/)
[![Python](https://img.shields.io/pypi/pyversions/ue-remote-exec.svg)](https://pypi.org/project/ue-remote-exec/)
[![Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)](https://github.com/rfioly/ue-remote-exec/blob/main/pyproject.toml)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/rfioly/ue-remote-exec/blob/main/LICENSE)

This is the transport layer extracted from
[ue5-editor-agent](https://github.com/rfioly/ue5-editor-agent), where it drives 31
editor tools and is tested against a live UE 5.8.2 editor on Windows. It is
published separately because the transport is the part other people need to
vendor, and because every other implementation of this channel I could find was
either abandoned or a hundred lines that stopped at "it pinged once".

```python
from ue_remote_exec import EditorSession

with EditorSession() as session:
    data = session.run("""
import unreal
sub = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
for actor in sub.get_all_level_actors()[:5]:
    print(actor.get_actor_label())
""")
    print(data["success"])
    for entry in data["output"]:
        print(entry["type"], entry["output"])
```

## Install

The long version of all four traps — with line numbers into the 5.8 source, and a
note on which ones nobody else has written down — is in
[docs/remote-execution-traps.md](https://github.com/rfioly/ue-remote-exec/blob/main/docs/remote-execution-traps.md).

```bash
pip install ue-remote-exec
```

## Editor setup (once per project)

1. **Edit → Plugins**, enable **Python Editor Script Plugin** and **Editor
   Scripting Utilities**.
2. **Edit → Project Settings** (project settings, not editor preferences), search
   for `Python`, enable **Enable Remote Execution?** and **Develop Mode**.
3. **Restart the editor.** These settings are read at startup.

Then:

```bash
ue-remote discover
ue-remote exec "import unreal; print(unreal.SystemLibrary.get_engine_version())"
```

## The four things that go wrong

These are not bugs in this library; they are properties of the channel. All four
were established by reading the 5.8 source rather than the documentation, which
covers none of them. Each one cost me an afternoon.

### 1. The TCP direction is inverted

You do not connect to the editor. **The editor connects to you.**

1. You listen on a local TCP port (you are the server).
2. You send `open_connection` over UDP: "connect to me at `x:y`".
3. The editor connects out as a TCP client — in the source it is literally
   `CommandChannelSocket->Connect(*CommandEndpoint.ToInternetAddr())`.
4. Only then can you send `command` and receive `command_result`.

Any implementation that tries to `socket.connect()` to the editor will hang.

### 2. `MulticastBindAddress` is one value used as three things

The editor builds its discovery socket like this:

```cpp
.BoundToAddress(MulticastBindAddress)
.JoinedToGroup(MulticastGroupEndpoint.Address, MulticastBindAddress)
.WithMulticastInterface(MulticastBindAddress)
```

Bind address, join interface, and egress interface — from a single value, which
defaults to `127.0.0.1` in 5.8. So a default install only joins the multicast
group on the loopback NIC, and a `ping` sent from your real NIC reaches nobody.

`ue-remote-exec` handles this by trying loopback first (`build_strategies()`), so
it works on a default install with no configuration. If discovery still returns
nothing, set **Project Settings → Plugins → Python → Advanced → Multicast Bind
Address** to `0.0.0.0` and restart — that is the configuration the engine treats
as "normal networking".

Two corollaries worth knowing:

- The TTL is also `0` by default (`RemoteExecutionMulticastTtl = 0`), and per the
  engine's own header comment, *0 is limited to the local host*. So "remote"
  execution is machine-local on **two** independent settings out of the box. For
  LAN use you must change both the bind address and the TTL, then restart.
- The editor's `pong` is **broadcast back to the multicast group**, not unicast to
  the requester. You must call `IP_ADD_MEMBERSHIP` yourself *and* bind port 6766.
  Multicast delivery matches on group address plus port, so binding a random port
  receives nothing.
### 3. `ioctl(SIO_UDP_CONNRESET, 0)` does not work, and mostly is not needed

The folklore fix for Windows UDP is `sock.ioctl(SIO_UDP_CONNRESET, 0)`. It cannot
work: CPython's `socket.ioctl()` accepts exactly three control codes —
`SIO_RCVALL`, `SIO_KEEPALIVE_VALS`, `SIO_LOOPBACK_FAST_PATH` — and raises
`ValueError: invalid ioctl command 2550136844` for anything else. The `except
OSError` that usually wraps it does not even catch that.

And the problem it claims to solve barely exists here. ICMP port-unreachable
comes from **unicast** sends; discovery only ever sends to the multicast group.
So the thing that actually keeps the receive loop alive is treating
`ConnectionResetError` as "nothing yet" on the `recvfrom` side — which is what
this library does. `_disable_udp_conn_reset()` still calls `WSAIoctl` directly
for the unicast cases, but it is belt-and-braces, not the mechanism.

### 4. The reference client hangs on a message of exactly 8192 bytes

`remote_execution.py` — Epic's own client, shipped inside the plugin — reads a
frame with `recv(8192)` and stops when it gets back **fewer than** 8192 bytes.
A `command_result` of exactly 8192 bytes therefore never terminates the loop; a
result split across reads gives `Unterminated string`; two queued results give
`Extra data`. `extract_json_objects()` here counts braces instead, so it does not
care how the bytes land.

## API

| | |
|---|---|
| `EditorSession(group, port, command_ip, timeout, verbose)` | context manager; `connect()` on entry, `close()` on exit |
| `session.connect() -> EditorNode` | discover, start the TCP server, ask the editor to connect back, accept |
| `session.run(code, exec_mode="ExecuteFile", timeout=120.0) -> dict` | send one command, return the `command_result` payload |
| `find_editor() -> EditorNode \| None` | discovery only, no session |
| `discover(group, port, timeout, verbose) -> list[dict]` | discovery with human-readable output |
| `extract_json_objects(buffer) -> (list[dict], bytes)` | the framing function, if you are writing your own transport |

`exec_mode` is `ExecuteFile` (a whole script), `ExecuteStatement` (one statement),
or `EvaluateStatement` (an expression whose value you want).

`session.run()` returns the raw `command_result` `data`: `success`, `command`,
`result`, and `output` (a list of `{type, output}` where type is `Info`,
`Warning`, or `Error`). **`success` is about whether the code raised, not whether
it did what you wanted** — a script that silently does nothing still reports
`success: True`. Check the state you care about, not the flag.

## Framing

Command channel frames have no length prefix and no terminator: bare JSON, one
object per send, `Strlen` bytes. TCP coalesces and fragments them anyway, so
`extract_json_objects()` counts braces while skipping string literals and escape
characters, and hands back the incomplete remainder for the next read. That
detail matters — a `command_result` whose `result` is itself dict-shaped used to
swallow the rest of the stream.

It takes `bytes`, not `str`: pass it the raw buffer and append whatever leftover
it returns to the next read. Do not decide completeness by size — that is exactly
the bug described in trap 4 above.

## What this is not

- Not a tool layer. It sends strings of Python and returns stdout. If you want
  typed tools, validation, and a model loop on top, that is
  [ue5-editor-agent](https://github.com/rfioly/ue5-editor-agent).
- Not a plugin. Everything it can do is what the Python API exposes; it cannot
  edit Blueprint graph nodes directly, for instance.
- Not for PIE or packaged builds. The Python plugin only runs inside the editor,
  which is the engine's design, not a limitation of this library.
- Not multi-editor. The first discovered node wins.

## Tests

```bash
python tests/run_all.py      # 21 tests, zero dependencies
```

The suite covers payload shapes, GUID source ids, JSON framing under every
chunking from 1 byte to 100 KB (concatenated objects, partial reads, braces and
escaped quotes inside strings), the loopback-first strategy order, and a real
multicast socket bind. It does not need an editor; nothing in it fakes a
discovery reply, because a fake reply would prove nothing about whether the real
one is parsed correctly.

Two tests exist only to keep a mistake from coming back: one asserts the source
contains no `socket.ioctl()` call carrying `SIO_UDP_CONNRESET`, the other asserts
`extract_json_objects()` returns exactly one object for a frame larger than 8192
bytes no matter how it is split.

## License

Apache-2.0. See [LICENSE](https://github.com/rfioly/ue-remote-exec/blob/main/LICENSE).
