world-engine-client 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ # Publish to PyPI via Trusted Publishing (OIDC — no API token stored anywhere).
2
+ # Trigger: pushing a version tag (v0.1.0). One-time setup on pypi.org required:
3
+ # add this repo+workflow as a "pending publisher" for the `world-engine` project
4
+ # (see README of the release process / the PR that added this file).
5
+ name: publish
6
+
7
+ on:
8
+ push:
9
+ tags: ["v*"]
10
+
11
+ jobs:
12
+ build:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: "3.12"
19
+ - run: python -m pip install build
20
+ - run: python -m build
21
+ - uses: actions/upload-artifact@v4
22
+ with:
23
+ name: dist
24
+ path: dist/
25
+
26
+ publish:
27
+ needs: build
28
+ runs-on: ubuntu-latest
29
+ environment: pypi
30
+ permissions:
31
+ id-token: write # OIDC for trusted publishing
32
+ steps:
33
+ - uses: actions/download-artifact@v4
34
+ with:
35
+ name: dist
36
+ path: dist/
37
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .venv/
7
+ .pytest_cache/
8
+ .ruff_cache/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: world-engine-client
3
+ Version: 0.1.0
4
+ Summary: Remote Gym-style Python client for a World Engine simulation server: connect(token) -> reset/step over HTTP.
5
+ Project-URL: Homepage, https://github.com/Grounded-Intelligence-Initiative/world-engine-client-python
6
+ Project-URL: Repository, https://github.com/Grounded-Intelligence-Initiative/world-engine-client-python
7
+ Author-email: Xiatao Sun <sunxiatao@gmail.com>
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: gaussian-splatting,gymnasium,real2sim,robotics,simulation
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: numpy>=1.24
21
+ Description-Content-Type: text/markdown
22
+
23
+ # world-engine-client
24
+
25
+ Remote Gym-style Python client for a World Engine
26
+ simulation server — a Gaussian-Splatting real-to-sim robot simulation framework.
27
+ Your Python connects with a token, becomes the (single) controller, and drives
28
+ the MuJoCo physics with `reset`/`step`, while every browser watching the
29
+ server's `viewer.html` sees the episode live.
30
+
31
+ ```bash
32
+ pip install world-engine-client
33
+ ```
34
+
35
+ Dependencies: numpy only. The import name is `world_engine_client` (the
36
+ `world_engine` module name belongs to the simulation server package).
37
+
38
+ ## Usage
39
+
40
+ Server side (prints the control token):
41
+
42
+ ```bash
43
+ world-engine --scenes-dir scenes serve --mode simulator \
44
+ --scene <scene> --task <task> --allow-remote-control
45
+ ```
46
+
47
+ Client side:
48
+
49
+ ```python
50
+ import world_engine_client as we_client
51
+
52
+ env = we_client.connect("<control token>", url="http://<host>:8080")
53
+ obs, info = env.reset(seed=0)
54
+ for _ in range(200):
55
+ action = my_policy(obs) # [-1,1]^4: [dx, dy, dz, gripper]
56
+ obs, reward, terminated, truncated, info = env.step(action)
57
+ if terminated or truncated:
58
+ obs, info = env.reset()
59
+ env.close()
60
+ ```
61
+
62
+ `obs` is a dict of numpy arrays: `proprio` (8: ee pos + quat wxyz + gripper),
63
+ `joint_positions`, `object_state` (pos+quat per body, sorted-id order) plus
64
+ `object_ids`. Camera-image observations ride the server's headless-renderer
65
+ path and are not yet exposed here (see the server repo's
66
+ `docs/remote_inference_api.md` for the design).
67
+
68
+ ## Semantics
69
+
70
+ - Exactly one controller may be bound; `connect(token, takeover=True)` revokes
71
+ a dead session.
72
+ - After `terminated`/`truncated` you must `reset()` (Gym semantics — the server
73
+ refuses further steps with `reset_required`).
74
+ - `RemoteEnv` is a context manager: `with we_client.connect(...) as env:`
75
+ releases the controller lock on exit.
76
+ - Errors are typed (`TokenError`, `ControllerConflictError`,
77
+ `ResetRequiredError`) and carry the server's "Possible fixes" hints.
78
+
79
+ ## Development
80
+
81
+ ```bash
82
+ pip install -e . && python -m pytest
83
+ ```
84
+
85
+ The wire-contract tests (real client against a real server) live in the server
86
+ repo: `tests/test_remote_control.py`.
@@ -0,0 +1,64 @@
1
+ # world-engine-client
2
+
3
+ Remote Gym-style Python client for a World Engine
4
+ simulation server — a Gaussian-Splatting real-to-sim robot simulation framework.
5
+ Your Python connects with a token, becomes the (single) controller, and drives
6
+ the MuJoCo physics with `reset`/`step`, while every browser watching the
7
+ server's `viewer.html` sees the episode live.
8
+
9
+ ```bash
10
+ pip install world-engine-client
11
+ ```
12
+
13
+ Dependencies: numpy only. The import name is `world_engine_client` (the
14
+ `world_engine` module name belongs to the simulation server package).
15
+
16
+ ## Usage
17
+
18
+ Server side (prints the control token):
19
+
20
+ ```bash
21
+ world-engine --scenes-dir scenes serve --mode simulator \
22
+ --scene <scene> --task <task> --allow-remote-control
23
+ ```
24
+
25
+ Client side:
26
+
27
+ ```python
28
+ import world_engine_client as we_client
29
+
30
+ env = we_client.connect("<control token>", url="http://<host>:8080")
31
+ obs, info = env.reset(seed=0)
32
+ for _ in range(200):
33
+ action = my_policy(obs) # [-1,1]^4: [dx, dy, dz, gripper]
34
+ obs, reward, terminated, truncated, info = env.step(action)
35
+ if terminated or truncated:
36
+ obs, info = env.reset()
37
+ env.close()
38
+ ```
39
+
40
+ `obs` is a dict of numpy arrays: `proprio` (8: ee pos + quat wxyz + gripper),
41
+ `joint_positions`, `object_state` (pos+quat per body, sorted-id order) plus
42
+ `object_ids`. Camera-image observations ride the server's headless-renderer
43
+ path and are not yet exposed here (see the server repo's
44
+ `docs/remote_inference_api.md` for the design).
45
+
46
+ ## Semantics
47
+
48
+ - Exactly one controller may be bound; `connect(token, takeover=True)` revokes
49
+ a dead session.
50
+ - After `terminated`/`truncated` you must `reset()` (Gym semantics — the server
51
+ refuses further steps with `reset_required`).
52
+ - `RemoteEnv` is a context manager: `with we_client.connect(...) as env:`
53
+ releases the controller lock on exit.
54
+ - Errors are typed (`TokenError`, `ControllerConflictError`,
55
+ `ResetRequiredError`) and carry the server's "Possible fixes" hints.
56
+
57
+ ## Development
58
+
59
+ ```bash
60
+ pip install -e . && python -m pytest
61
+ ```
62
+
63
+ The wire-contract tests (real client against a real server) live in the server
64
+ repo: `tests/test_remote_control.py`.
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "world-engine-client"
7
+ version = "0.1.0"
8
+ description = "Remote Gym-style Python client for a World Engine simulation server: connect(token) -> reset/step over HTTP."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "Xiatao Sun", email = "sunxiatao@gmail.com" }]
13
+ keywords = ["robotics", "simulation", "gymnasium", "gaussian-splatting", "real2sim"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Science/Research",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
23
+ ]
24
+ dependencies = [
25
+ "numpy>=1.24",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/Grounded-Intelligence-Initiative/world-engine-client-python"
30
+ Repository = "https://github.com/Grounded-Intelligence-Initiative/world-engine-client-python"
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/world_engine_client"]
34
+
35
+ [tool.ruff]
36
+ line-length = 100
37
+
38
+ [tool.ruff.lint]
39
+ select = ["E", "F", "I", "B", "UP", "W"]
@@ -0,0 +1,37 @@
1
+ """world-engine-client (import name ``world_engine_client``): drive a remote
2
+ World Engine sim with Gym semantics.
3
+
4
+ import world_engine_client as we_client
5
+ env = we_client.connect("<control token>", url="http://<host>:8080")
6
+ obs, info = env.reset(seed=0)
7
+ for _ in range(100):
8
+ obs, reward, terminated, truncated, info = env.step([0.1, 0, -0.2, -1.0])
9
+ if terminated or truncated:
10
+ obs, info = env.reset()
11
+ env.close()
12
+
13
+ The token is printed by ``world-engine serve --mode simulator
14
+ --allow-remote-control``. Every browser viewing that server's viewer.html sees
15
+ your episode live. Stdlib HTTP + numpy only — no gymnasium requirement (the
16
+ API is 5-tuple compatible).
17
+ """
18
+
19
+ from .env import RemoteEnv, connect
20
+ from .errors import (
21
+ ControllerConflictError,
22
+ ProtocolError,
23
+ ResetRequiredError,
24
+ TokenError,
25
+ WorldEngineClientError,
26
+ )
27
+
28
+ __all__ = [
29
+ "connect",
30
+ "RemoteEnv",
31
+ "WorldEngineClientError",
32
+ "TokenError",
33
+ "ControllerConflictError",
34
+ "ResetRequiredError",
35
+ "ProtocolError",
36
+ ]
37
+ __version__ = "0.1.0"
@@ -0,0 +1,132 @@
1
+ """RemoteEnv: a Gymnasium-shaped client for the World Engine /control API.
2
+
3
+ Synchronous by design — an inference loop is synchronous. Transport is plain
4
+ HTTP POST (stdlib urllib): one round-trip per step, which the lockstep
5
+ semantics require anyway. Obs arrays come back as JSON lists and are converted
6
+ to numpy here; camera images are a future obs key (see the design doc §4).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import urllib.error
13
+ import urllib.request
14
+
15
+ import numpy as np
16
+
17
+ from .errors import WorldEngineClientError, raise_for
18
+
19
+ _PROTO = 1
20
+
21
+
22
+ def connect(
23
+ token: str,
24
+ url: str = "http://127.0.0.1:8080",
25
+ *,
26
+ takeover: bool = False,
27
+ timeout: float = 30.0,
28
+ ) -> RemoteEnv:
29
+ """Bind to the server as THE controller and return a ready RemoteEnv.
30
+
31
+ ``token`` is printed by ``world-engine serve --allow-remote-control``.
32
+ ``takeover=True`` revokes a controller that died without releasing."""
33
+ env = RemoteEnv(url.rstrip("/"), token, timeout=timeout)
34
+ env._connect(takeover=takeover)
35
+ return env
36
+
37
+
38
+ class RemoteEnv:
39
+ """reset/step/close over HTTP. Use via :func:`connect`."""
40
+
41
+ def __init__(self, base_url: str, token: str, *, timeout: float = 30.0):
42
+ self._base = base_url
43
+ self._token = token
44
+ self._timeout = timeout
45
+ self._session_id: str | None = None
46
+ self.metadata: dict = {}
47
+ self.action_dim: int = 4
48
+ self.observation_keys: list[str] = []
49
+
50
+ # ----- Gym API ------------------------------------------------------------ #
51
+ def reset(self, *, seed: int | None = None, options: dict | None = None):
52
+ reply = self._post("/control/reset", {"seed": seed})
53
+ return self._np_obs(reply["obs"]), reply.get("info", {})
54
+
55
+ def step(self, action):
56
+ a = np.asarray(action, dtype=np.float32).reshape(-1)
57
+ reply = self._post("/control/step", {"action": [float(x) for x in a]})
58
+ return (
59
+ self._np_obs(reply["obs"]),
60
+ float(reply["reward"]),
61
+ bool(reply["terminated"]),
62
+ bool(reply["truncated"]),
63
+ reply.get("info", {}),
64
+ )
65
+
66
+ def close(self) -> None:
67
+ if self._session_id is None:
68
+ return
69
+ try:
70
+ self._post("/control/release", {})
71
+ except WorldEngineClientError:
72
+ pass # already revoked / server gone — nothing to release
73
+ self._session_id = None
74
+
75
+ def __enter__(self) -> RemoteEnv:
76
+ return self
77
+
78
+ def __exit__(self, *exc) -> None:
79
+ self.close()
80
+
81
+ # ----- wire ----------------------------------------------------------------#
82
+ def _connect(self, *, takeover: bool) -> None:
83
+ reply = self._post(
84
+ "/control/connect", {"proto": _PROTO, "takeover": takeover}, with_session=False
85
+ )
86
+ self._session_id = reply["session_id"]
87
+ self.metadata = reply.get("env", {})
88
+ self.action_dim = int(self.metadata.get("action_dim", 4))
89
+ self.observation_keys = list(self.metadata.get("observation_keys", []))
90
+
91
+ def _post(self, path: str, payload: dict, *, with_session: bool = True) -> dict:
92
+ body = dict(payload)
93
+ if with_session:
94
+ body["session_id"] = self._session_id
95
+ req = urllib.request.Request(
96
+ self._base + path,
97
+ data=json.dumps(body).encode("utf-8"),
98
+ method="POST",
99
+ headers={
100
+ "Content-Type": "application/json",
101
+ "X-We-Control-Token": self._token,
102
+ },
103
+ )
104
+ try:
105
+ with urllib.request.urlopen(req, timeout=self._timeout) as r:
106
+ reply = json.loads(r.read().decode("utf-8"))
107
+ except urllib.error.HTTPError as e:
108
+ try:
109
+ reply = json.loads(e.read().decode("utf-8"))
110
+ except ValueError:
111
+ raise WorldEngineClientError(f"HTTP {e.code} from {path}") from e
112
+ except (urllib.error.URLError, OSError) as e:
113
+ raise WorldEngineClientError(
114
+ f"cannot reach the World Engine server at {self._base}",
115
+ fixes=[
116
+ "Is `world-engine serve --mode simulator --allow-remote-control` running?",
117
+ "Check the url= argument (host/port, and any SSH -L / Tailscale routing).",
118
+ ],
119
+ ) from e
120
+ if not reply.get("ok"):
121
+ raise_for(reply)
122
+ return reply
123
+
124
+ @staticmethod
125
+ def _np_obs(obs: dict) -> dict:
126
+ out: dict = {}
127
+ for k, v in obs.items():
128
+ if isinstance(v, list) and v and isinstance(v[0], (int, float)):
129
+ out[k] = np.asarray(v, dtype=np.float32)
130
+ else:
131
+ out[k] = v
132
+ return out
@@ -0,0 +1,53 @@
1
+ """Client-side exceptions mirroring the server's error codes.
2
+
3
+ Server replies carry ``{ok:false, code, error, fixes:[...]}``; ``raise_for``
4
+ maps codes to typed exceptions and renders the fixes into the message the same
5
+ way the World Engine CLI does ("Possible fixes:" block).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ class WorldEngineClientError(RuntimeError):
12
+ """Base error; carries the server error code when one exists."""
13
+
14
+ def __init__(self, message: str, *, code: str | None = None, fixes: list[str] | None = None):
15
+ if fixes:
16
+ message += "\n Possible fixes:\n" + "\n".join(
17
+ f" {i + 1}. {f}" for i, f in enumerate(fixes)
18
+ )
19
+ super().__init__(message)
20
+ self.code = code
21
+
22
+
23
+ class TokenError(WorldEngineClientError):
24
+ """The control token was rejected (wrong token, or the server was started
25
+ without --allow-remote-control)."""
26
+
27
+
28
+ class ControllerConflictError(WorldEngineClientError):
29
+ """Another controller is bound; pass takeover=True to seize control."""
30
+
31
+
32
+ class ResetRequiredError(WorldEngineClientError):
33
+ """step() outside an active episode — call reset() first."""
34
+
35
+
36
+ class ProtocolError(WorldEngineClientError):
37
+ """The server said something this client version does not understand."""
38
+
39
+
40
+ _BY_CODE = {
41
+ "bad_token": TokenError,
42
+ "controller_exists": ControllerConflictError,
43
+ "reset_required": ResetRequiredError,
44
+ "bad_session": ControllerConflictError,
45
+ "not_connected": ProtocolError,
46
+ }
47
+
48
+
49
+ def raise_for(reply: dict) -> None:
50
+ """Raise the typed exception for a ``{ok:false}`` server reply."""
51
+ code = reply.get("code")
52
+ cls = _BY_CODE.get(code, WorldEngineClientError)
53
+ raise cls(reply.get("error", "unknown server error"), code=code, fixes=reply.get("fixes"))