digiarena 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,39 @@
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 `digiarena` project
4
+ # (pypi.org → Your projects → Publishing → GitHub:
5
+ # owner Grounded-Intelligence-Initiative, repo digiarena-client-python,
6
+ # workflow publish.yml, environment pypi).
7
+ name: publish
8
+
9
+ on:
10
+ push:
11
+ tags: ["v*"]
12
+
13
+ jobs:
14
+ build:
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: "3.12"
21
+ - run: python -m pip install build
22
+ - run: python -m build
23
+ - uses: actions/upload-artifact@v4
24
+ with:
25
+ name: dist
26
+ path: dist/
27
+
28
+ publish:
29
+ needs: build
30
+ runs-on: ubuntu-latest
31
+ environment: pypi
32
+ permissions:
33
+ id-token: write # OIDC for trusted publishing
34
+ steps:
35
+ - uses: actions/download-artifact@v4
36
+ with:
37
+ name: dist
38
+ path: dist/
39
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,5 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ .venv/
5
+ .pytest_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,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: digiarena
3
+ Version: 0.1.0
4
+ Summary: Python SDK for DigiArena (digiarena.org): browse hosted robot-simulation scenes, deploy cloud gyms, submit to benchmarks.
5
+ Project-URL: Homepage, https://digiarena.org
6
+ Project-URL: Repository, https://github.com/Grounded-Intelligence-Initiative/digiarena-client-python
7
+ Project-URL: Documentation, https://digiarena.org/docs/api
8
+ Author-email: Xiatao Sun <sunxiatao@gmail.com>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: benchmark,gaussian-splatting,gymnasium,real2sim,robotics,simulation
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: world-engine-client>=0.2
22
+ Description-Content-Type: text/markdown
23
+
24
+ # digiarena (PyPI: `digiarena`)
25
+
26
+ Python SDK for [DigiArena](https://digiarena.org) — browse hosted
27
+ robot-simulation scenes, deploy them as cloud gyms, and submit to benchmarks.
28
+
29
+ ```bash
30
+ pip install digiarena
31
+ ```
32
+
33
+ ```python
34
+ import digiarena as da
35
+
36
+ da.login() # paste an API key from digiarena.org → Settings
37
+ scenes = da.scenes.list(query="kitchen")
38
+ gym = da.deploy(scene="kitchen_001", task="pick_mug_to_sink")
39
+ env = gym.connect() # → world_engine_client.RemoteEnv
40
+ obs, info = env.reset(seed=0)
41
+ obs, r, term, trunc, info = env.step(action)
42
+ gym.close()
43
+ ```
44
+
45
+ CLI with the same surface:
46
+
47
+ ```
48
+ digiarena login
49
+ digiarena scenes list --query kitchen
50
+ digiarena deploy --scene kitchen_001
51
+ digiarena leaderboard tabletop-v1
52
+ digiarena usage
53
+ ```
54
+
55
+ ## Layering
56
+
57
+ `digiarena` depends on and reuses
58
+ [`world-engine-client`](https://github.com/Grounded-Intelligence-Initiative/world-engine-client-python)
59
+ (`connect(token, url) → RemoteEnv`). This package covers everything from your
60
+ account to that token — scene gallery, cloud deploy, benchmark submission,
61
+ leaderboards, usage — and never reimplements the wire protocol.
62
+
63
+ - Zero heavy dependencies: importing `digiarena` pulls stdlib + numpy only
64
+ (via `world-engine-client`). No torch / gymnasium / opencv.
65
+ - Every call hits the public REST API (`/api/v1/*`) with
66
+ `Authorization: Bearer da_live_...` — the SDK is a thin wrapper you could
67
+ replace with curl.
68
+ - Typed errors with actionable "Possible fixes" (the World Engine style).
69
+ - Endpoints still in later platform milestones (deploy orchestration,
70
+ benchmark submission) raise `NotImplementedYetError` with the server's own
71
+ guidance — the SDK surface is stable ahead of them.
72
+
73
+ Scene content never transits your machine: there is no upload()/download().
74
+ Content is authored in the platform's browser editor; public scenes are used
75
+ via `scene.fork()` + `da.deploy()`.
76
+
77
+ ## Credentials
78
+
79
+ `DIGIARENA_API_KEY` env var (CI/batch) → `~/.config/digiarena/credentials`
80
+ (written by `da.login()` / `digiarena login`, mode 0600).
81
+ `DIGIARENA_API_URL` overrides the endpoint for staging deployments.
@@ -0,0 +1,58 @@
1
+ # digiarena (PyPI: `digiarena`)
2
+
3
+ Python SDK for [DigiArena](https://digiarena.org) — browse hosted
4
+ robot-simulation scenes, deploy them as cloud gyms, and submit to benchmarks.
5
+
6
+ ```bash
7
+ pip install digiarena
8
+ ```
9
+
10
+ ```python
11
+ import digiarena as da
12
+
13
+ da.login() # paste an API key from digiarena.org → Settings
14
+ scenes = da.scenes.list(query="kitchen")
15
+ gym = da.deploy(scene="kitchen_001", task="pick_mug_to_sink")
16
+ env = gym.connect() # → world_engine_client.RemoteEnv
17
+ obs, info = env.reset(seed=0)
18
+ obs, r, term, trunc, info = env.step(action)
19
+ gym.close()
20
+ ```
21
+
22
+ CLI with the same surface:
23
+
24
+ ```
25
+ digiarena login
26
+ digiarena scenes list --query kitchen
27
+ digiarena deploy --scene kitchen_001
28
+ digiarena leaderboard tabletop-v1
29
+ digiarena usage
30
+ ```
31
+
32
+ ## Layering
33
+
34
+ `digiarena` depends on and reuses
35
+ [`world-engine-client`](https://github.com/Grounded-Intelligence-Initiative/world-engine-client-python)
36
+ (`connect(token, url) → RemoteEnv`). This package covers everything from your
37
+ account to that token — scene gallery, cloud deploy, benchmark submission,
38
+ leaderboards, usage — and never reimplements the wire protocol.
39
+
40
+ - Zero heavy dependencies: importing `digiarena` pulls stdlib + numpy only
41
+ (via `world-engine-client`). No torch / gymnasium / opencv.
42
+ - Every call hits the public REST API (`/api/v1/*`) with
43
+ `Authorization: Bearer da_live_...` — the SDK is a thin wrapper you could
44
+ replace with curl.
45
+ - Typed errors with actionable "Possible fixes" (the World Engine style).
46
+ - Endpoints still in later platform milestones (deploy orchestration,
47
+ benchmark submission) raise `NotImplementedYetError` with the server's own
48
+ guidance — the SDK surface is stable ahead of them.
49
+
50
+ Scene content never transits your machine: there is no upload()/download().
51
+ Content is authored in the platform's browser editor; public scenes are used
52
+ via `scene.fork()` + `da.deploy()`.
53
+
54
+ ## Credentials
55
+
56
+ `DIGIARENA_API_KEY` env var (CI/batch) → `~/.config/digiarena/credentials`
57
+ (written by `da.login()` / `digiarena login`, mode 0600).
58
+ `DIGIARENA_API_URL` overrides the endpoint for staging deployments.
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "digiarena"
7
+ version = "0.1.0"
8
+ description = "Python SDK for DigiArena (digiarena.org): browse hosted robot-simulation scenes, deploy cloud gyms, submit to benchmarks."
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", "benchmark", "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
+ # 分层原则(07 文档):digiarena 只封装「从账号到 token+URL」,wire 协议
25
+ # 全部复用 world-engine-client;HTTP 走 stdlib urllib——零额外依赖。
26
+ dependencies = [
27
+ "world-engine-client>=0.2",
28
+ ]
29
+
30
+ [project.scripts]
31
+ digiarena = "digiarena.cli:main"
32
+
33
+ [project.urls]
34
+ Homepage = "https://digiarena.org"
35
+ Repository = "https://github.com/Grounded-Intelligence-Initiative/digiarena-client-python"
36
+ Documentation = "https://digiarena.org/docs/api"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/digiarena"]
40
+
41
+ [tool.ruff]
42
+ line-length = 100
43
+
44
+ [tool.ruff.lint]
45
+ select = ["E", "F", "I", "B", "UP", "W"]
46
+
47
+ [dependency-groups]
48
+ dev = ["pytest>=8"]
@@ -0,0 +1,64 @@
1
+ """digiarena — the DigiArena platform SDK (PyPI: ``digiarena``).
2
+
3
+ import digiarena as da
4
+
5
+ da.login() # paste an API key from digiarena.org → Settings
6
+ scenes = da.scenes.list(query="kitchen")
7
+ gym = da.deploy(scene="kitchen_001", task="pick_mug_to_sink")
8
+ env = gym.connect() # → world_engine_client.RemoteEnv
9
+ obs, info = env.reset(seed=0)
10
+ obs, r, term, trunc, info = env.step(action)
11
+ gym.close()
12
+
13
+ Layering: ``world-engine-client`` turns token+URL into a Gym env (the wire
14
+ protocol); ``digiarena`` covers everything from your account to that token —
15
+ scene gallery, cloud deploy, benchmarks, leaderboard, usage. Importing this
16
+ package never pulls heavy dependencies (no torch / gymnasium / opencv).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ __version__ = "0.1.0"
22
+
23
+ from . import benchmarks, scenes # noqa: E402 (submodule namespaces)
24
+ from .config import login # noqa: E402
25
+ from .errors import ( # noqa: E402
26
+ ApiError,
27
+ AuthError,
28
+ DeployTimeoutError,
29
+ DigiArenaError,
30
+ NotImplementedYetError,
31
+ QuotaExceededError,
32
+ RateLimitedError,
33
+ SceneExistsError,
34
+ SceneNotFoundError,
35
+ )
36
+ from .gyms import GymHandle, deploy, list_gyms # noqa: E402
37
+ from .usage import usage # noqa: E402
38
+
39
+
40
+ def leaderboard(benchmark: str):
41
+ """Shortcut for :func:`digiarena.benchmarks.leaderboard`."""
42
+ return benchmarks.leaderboard(benchmark)
43
+
44
+
45
+ __all__ = [
46
+ "__version__",
47
+ "login",
48
+ "deploy",
49
+ "list_gyms",
50
+ "leaderboard",
51
+ "usage",
52
+ "GymHandle",
53
+ "scenes",
54
+ "benchmarks",
55
+ "DigiArenaError",
56
+ "AuthError",
57
+ "RateLimitedError",
58
+ "SceneNotFoundError",
59
+ "SceneExistsError",
60
+ "QuotaExceededError",
61
+ "DeployTimeoutError",
62
+ "NotImplementedYetError",
63
+ "ApiError",
64
+ ]
@@ -0,0 +1,82 @@
1
+ """Minimal stdlib HTTP layer for the DigiArena control plane.
2
+
3
+ Every call goes to the public REST API (``/api/v1/*``) with
4
+ ``Authorization: Bearer da_live_...`` — the SDK is a thin wrapper anyone could
5
+ replace with curl. stdlib ``urllib`` only (zero-dependency principle).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+
15
+ from . import __version__ as _sdk_version
16
+ from .config import api_base, api_key
17
+ from .errors import ApiError, AuthError, raise_for
18
+
19
+ _TIMEOUT_S = 30.0
20
+
21
+
22
+ def request(
23
+ method: str,
24
+ path: str,
25
+ *,
26
+ query: dict[str, str] | None = None,
27
+ body: dict | None = None,
28
+ auth: bool = True,
29
+ ) -> dict:
30
+ """One control-plane call → parsed ``{ok:true, ...}`` payload.
31
+
32
+ ``{ok:false}`` replies raise the typed exception for their code; transport
33
+ failures raise :class:`ApiError` with the underlying reason.
34
+ """
35
+ url = api_base().rstrip("/") + path
36
+ if query:
37
+ url += "?" + urllib.parse.urlencode({k: v for k, v in query.items() if v is not None})
38
+ headers = {
39
+ "User-Agent": f"digiarena-python/{_sdk_version}",
40
+ "Accept": "application/json",
41
+ }
42
+ if auth:
43
+ key = api_key()
44
+ if not key:
45
+ raise AuthError(
46
+ "No API key configured.",
47
+ code="unauthorized",
48
+ fixes=[
49
+ "Run `digiarena login` (or da.login()) and paste a key from "
50
+ "digiarena.org → Settings",
51
+ "Or set the DIGIARENA_API_KEY environment variable",
52
+ ],
53
+ )
54
+ headers["Authorization"] = f"Bearer {key}"
55
+ data = None
56
+ if body is not None:
57
+ data = json.dumps(body).encode("utf-8")
58
+ headers["Content-Type"] = "application/json"
59
+
60
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
61
+ try:
62
+ with urllib.request.urlopen(req, timeout=_TIMEOUT_S) as resp:
63
+ payload = json.loads(resp.read().decode("utf-8"))
64
+ except urllib.error.HTTPError as e:
65
+ try:
66
+ payload = json.loads(e.read().decode("utf-8"))
67
+ except Exception:
68
+ raise ApiError(f"HTTP {e.code} from {path}", status=e.code) from e
69
+ raise_for(e.code, payload)
70
+ raise AssertionError("unreachable") from None # raise_for always raises
71
+ except urllib.error.URLError as e:
72
+ raise ApiError(
73
+ f"Cannot reach the DigiArena API at {api_base()}: {e.reason}",
74
+ fixes=[
75
+ "Check your network connection",
76
+ "Override the endpoint with DIGIARENA_API_URL if you are "
77
+ "targeting a staging deployment",
78
+ ],
79
+ ) from e
80
+ if not payload.get("ok", False):
81
+ raise_for(200, payload)
82
+ return payload
@@ -0,0 +1,38 @@
1
+ """Benchmarks: list / leaderboard / submissions.
2
+
3
+ Benchmark ids are ``{slug}-v{version}`` — the protocol (episode count, seed
4
+ rules, max_steps) is frozen per version so leaderboard scores stay comparable.
5
+ Submission endpoints are part of a later milestone; the SDK surface is final.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from ._http import request
13
+
14
+
15
+ def list() -> list[dict[str, Any]]: # noqa: A001 - mirrors da.benchmarks.list()
16
+ """Published benchmarks (public, no key needed)."""
17
+ return request("GET", "/api/v1/benchmarks", auth=False)["benchmarks"]
18
+
19
+
20
+ def leaderboard(benchmark: str) -> list[dict[str, Any]]:
21
+ """The public leaderboard of one benchmark (pandas-free list of dicts)."""
22
+ return request("GET", f"/api/v1/benchmarks/{benchmark}/leaderboard", auth=False)[
23
+ "leaderboard"
24
+ ]
25
+
26
+
27
+ def submit_live(benchmark: str, *, entry_name: str) -> dict[str, Any]:
28
+ """Create a live-client submission (your policy runs on your machine)."""
29
+ return request(
30
+ "POST",
31
+ f"/api/v1/benchmarks/{benchmark}/submissions",
32
+ body={"mode": "live", "entry_name": entry_name},
33
+ )
34
+
35
+
36
+ def submission(benchmark: str, submission_id: str) -> dict[str, Any]:
37
+ """Progress/result of one submission."""
38
+ return request("GET", f"/api/v1/benchmarks/{benchmark}/submissions/{submission_id}")
@@ -0,0 +1,120 @@
1
+ """``digiarena`` CLI — the same surface as the SDK, for shells and CI.
2
+
3
+ digiarena login
4
+ digiarena scenes list [--query q] [--mine]
5
+ digiarena scenes get <owner/slug>
6
+ digiarena scenes create <slug> [--name n] [--public]
7
+ digiarena deploy --scene <owner/slug> [--task t]
8
+ digiarena gyms list / close <id> / logs <id>
9
+ digiarena benchmarks list
10
+ digiarena leaderboard <benchmark>
11
+ digiarena usage
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import sys
19
+
20
+
21
+ def _print(obj: object) -> None:
22
+ print(json.dumps(obj, indent=2, ensure_ascii=False, default=str))
23
+
24
+
25
+ def main(argv: list[str] | None = None) -> int:
26
+ parser = argparse.ArgumentParser(
27
+ prog="digiarena", description="DigiArena platform CLI (digiarena.org)"
28
+ )
29
+ sub = parser.add_subparsers(dest="cmd", required=True)
30
+
31
+ sub.add_parser("login", help="store an API key for subsequent calls")
32
+
33
+ p_scenes = sub.add_parser("scenes", help="scene gallery")
34
+ scenes_sub = p_scenes.add_subparsers(dest="scenes_cmd", required=True)
35
+ p_list = scenes_sub.add_parser("list")
36
+ p_list.add_argument("--query")
37
+ p_list.add_argument("--mine", action="store_true", help="your scenes (needs the API key)")
38
+ p_get = scenes_sub.add_parser("get")
39
+ p_get.add_argument("scene_id", metavar="owner/slug")
40
+ p_create = scenes_sub.add_parser("create")
41
+ p_create.add_argument("slug")
42
+ p_create.add_argument("--name")
43
+ p_create.add_argument("--description", default="")
44
+ p_create.add_argument("--public", action="store_true")
45
+
46
+ p_deploy = sub.add_parser("deploy", help="deploy a scene as a cloud gym")
47
+ p_deploy.add_argument("--scene", required=True)
48
+ p_deploy.add_argument("--task")
49
+ p_deploy.add_argument("--tier", default="auto")
50
+
51
+ p_gyms = sub.add_parser("gyms", help="your gym sessions")
52
+ gyms_sub = p_gyms.add_subparsers(dest="gyms_cmd", required=True)
53
+ gyms_sub.add_parser("list")
54
+ p_close = gyms_sub.add_parser("close")
55
+ p_close.add_argument("gym_id")
56
+ p_logs = gyms_sub.add_parser("logs")
57
+ p_logs.add_argument("gym_id")
58
+ p_logs.add_argument("--tail", type=int, default=100)
59
+
60
+ p_bm = sub.add_parser("benchmarks", help="published benchmarks")
61
+ bm_sub = p_bm.add_subparsers(dest="bm_cmd", required=True)
62
+ bm_sub.add_parser("list")
63
+
64
+ p_lb = sub.add_parser("leaderboard")
65
+ p_lb.add_argument("benchmark", metavar="slug-vN")
66
+
67
+ sub.add_parser("usage", help="this month's quota/usage")
68
+
69
+ args = parser.parse_args(argv)
70
+
71
+ import digiarena as da
72
+
73
+ try:
74
+ if args.cmd == "login":
75
+ da.login()
76
+ elif args.cmd == "scenes":
77
+ if args.scenes_cmd == "list":
78
+ _print([s.__dict__ for s in da.scenes.list(args.query, public=not args.mine)])
79
+ elif args.scenes_cmd == "get":
80
+ _print(da.scenes.get(args.scene_id).__dict__)
81
+ elif args.scenes_cmd == "create":
82
+ _print(
83
+ da.scenes.create(
84
+ args.slug,
85
+ name=args.name,
86
+ description=args.description,
87
+ public=args.public,
88
+ ).__dict__
89
+ )
90
+ elif args.cmd == "deploy":
91
+ gym = da.deploy(args.scene, task=args.task, tier=args.tier)
92
+ _print(gym.__dict__)
93
+ print(
94
+ "\n# connect once ready:\n"
95
+ "import digiarena as da\n"
96
+ 'env = da.list_gyms()[0].connect() # or keep the GymHandle from deploy',
97
+ file=sys.stderr,
98
+ )
99
+ elif args.cmd == "gyms":
100
+ if args.gyms_cmd == "list":
101
+ _print([g.__dict__ for g in da.list_gyms()])
102
+ elif args.gyms_cmd == "close":
103
+ da.GymHandle(gym_id=args.gym_id, status="ready").close()
104
+ print("closed")
105
+ elif args.gyms_cmd == "logs":
106
+ print(da.GymHandle(gym_id=args.gym_id, status="ready").logs(tail=args.tail))
107
+ elif args.cmd == "benchmarks":
108
+ _print(da.benchmarks.list())
109
+ elif args.cmd == "leaderboard":
110
+ _print(da.leaderboard(args.benchmark))
111
+ elif args.cmd == "usage":
112
+ _print(da.usage())
113
+ except da.DigiArenaError as e:
114
+ print(f"error: {e}", file=sys.stderr)
115
+ return 1
116
+ return 0
117
+
118
+
119
+ if __name__ == "__main__":
120
+ raise SystemExit(main())
@@ -0,0 +1,78 @@
1
+ """Credentials + endpoint resolution.
2
+
3
+ Precedence (CI/batch first): ``DIGIARENA_API_KEY`` env var →
4
+ ``~/.config/digiarena/credentials`` (INI-less ``key = value`` lines, 0600).
5
+ The endpoint defaults to production; ``DIGIARENA_API_URL`` overrides for
6
+ staging/local development.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from pathlib import Path
13
+
14
+ DEFAULT_API_URL = "https://digiarena.org"
15
+
16
+ _CRED_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "digiarena"
17
+ _CRED_FILE = _CRED_DIR / "credentials"
18
+
19
+
20
+ def api_base() -> str:
21
+ return os.environ.get("DIGIARENA_API_URL", DEFAULT_API_URL)
22
+
23
+
24
+ def _read_credentials() -> dict[str, str]:
25
+ if not _CRED_FILE.is_file():
26
+ return {}
27
+ out: dict[str, str] = {}
28
+ for line in _CRED_FILE.read_text().splitlines():
29
+ line = line.strip()
30
+ if not line or line.startswith("#") or "=" not in line:
31
+ continue
32
+ k, v = line.split("=", 1)
33
+ out[k.strip()] = v.strip()
34
+ return out
35
+
36
+
37
+ def api_key() -> str | None:
38
+ env = os.environ.get("DIGIARENA_API_KEY")
39
+ if env:
40
+ return env
41
+ return _read_credentials().get("api_key")
42
+
43
+
44
+ def save_api_key(key: str) -> Path:
45
+ """Persist the key to the credentials file (0600). Returns the path."""
46
+ _CRED_DIR.mkdir(parents=True, exist_ok=True)
47
+ creds = _read_credentials()
48
+ creds["api_key"] = key
49
+ _CRED_FILE.write_text("".join(f"{k} = {v}\n" for k, v in creds.items()))
50
+ _CRED_FILE.chmod(0o600)
51
+ return _CRED_FILE
52
+
53
+
54
+ def login(key: str | None = None) -> None:
55
+ """Store an API key for subsequent calls.
56
+
57
+ Interactive: called with no argument, prompts for the key (create one on
58
+ digiarena.org → Settings). Non-interactive callers pass ``key=`` directly
59
+ or set ``DIGIARENA_API_KEY``.
60
+ """
61
+ if key is None:
62
+ try:
63
+ key = input("Paste your DigiArena API key (da_live_...): ").strip()
64
+ except EOFError: # non-interactive shells
65
+ key = ""
66
+ if not key:
67
+ from .errors import AuthError
68
+
69
+ raise AuthError(
70
+ "No API key provided.",
71
+ code="unauthorized",
72
+ fixes=[
73
+ "Create a key on digiarena.org → Settings",
74
+ "Or set the DIGIARENA_API_KEY environment variable",
75
+ ],
76
+ )
77
+ path = save_api_key(key)
78
+ print(f"API key saved to {path}")
@@ -0,0 +1,85 @@
1
+ """Typed errors mirroring the DigiArena control-plane error contract.
2
+
3
+ Every ``/api/v1/*`` error reply carries ``{ok:false, code, error, fixes:[...]}``;
4
+ :func:`raise_for` maps the code to a typed exception and renders the fixes into
5
+ the message the same way the World Engine CLI does ("Possible fixes:" block).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ class DigiArenaError(RuntimeError):
12
+ """Base error; carries the server error code + HTTP status when present."""
13
+
14
+ def __init__(
15
+ self,
16
+ message: str,
17
+ *,
18
+ code: str | None = None,
19
+ status: int | None = None,
20
+ fixes: list[str] | None = None,
21
+ ):
22
+ if fixes:
23
+ message += "\n Possible fixes:\n" + "\n".join(
24
+ f" {i + 1}. {f}" for i, f in enumerate(fixes)
25
+ )
26
+ super().__init__(message)
27
+ self.code = code
28
+ self.status = status
29
+
30
+
31
+ class AuthError(DigiArenaError):
32
+ """Missing/invalid API key. Create one on digiarena.org → Settings, then
33
+ ``da.login()`` (or set the DIGIARENA_API_KEY environment variable)."""
34
+
35
+
36
+ class RateLimitedError(DigiArenaError):
37
+ """The API key hit its rate limit — retry with exponential backoff."""
38
+
39
+
40
+ class SceneNotFoundError(DigiArenaError):
41
+ """The scene id does not exist or is not visible to this account."""
42
+
43
+
44
+ class SceneExistsError(DigiArenaError):
45
+ """A scene with this slug already exists in your namespace."""
46
+
47
+
48
+ class QuotaExceededError(DigiArenaError):
49
+ """The account's compute quota or concurrent-session limit is exhausted."""
50
+
51
+
52
+ class DeployTimeoutError(DigiArenaError):
53
+ """The gym did not reach ready state within the polling window."""
54
+
55
+
56
+ class NotImplementedYetError(DigiArenaError):
57
+ """The endpoint is part of a later milestone (HTTP 501). The SDK surface
58
+ is stable; retry after the platform ships the feature."""
59
+
60
+
61
+ class ApiError(DigiArenaError):
62
+ """Any other structured control-plane error."""
63
+
64
+
65
+ _BY_CODE: dict[str, type[DigiArenaError]] = {
66
+ "unauthorized": AuthError,
67
+ "rate_limited": RateLimitedError,
68
+ "scene_not_found": SceneNotFoundError,
69
+ "scene_exists": SceneExistsError,
70
+ "quota_exceeded": QuotaExceededError,
71
+ "session_limit": QuotaExceededError,
72
+ "not_implemented": NotImplementedYetError,
73
+ }
74
+
75
+
76
+ def raise_for(status: int, payload: dict) -> None:
77
+ """Raise the typed exception for an ``{ok:false, ...}`` reply."""
78
+ code = payload.get("code")
79
+ cls = _BY_CODE.get(code or "", ApiError)
80
+ raise cls(
81
+ str(payload.get("error") or f"HTTP {status}"),
82
+ code=code,
83
+ status=status,
84
+ fixes=list(payload.get("fixes") or []),
85
+ )
@@ -0,0 +1,114 @@
1
+ """Cloud gym deploy: ``da.deploy(...)`` → :class:`GymHandle` → ``connect()``.
2
+
3
+ The deploy endpoint is part of the orchestration milestone; until the platform
4
+ ships it, ``deploy()`` raises :class:`~digiarena.errors.NotImplementedYetError`
5
+ with the server's own guidance — the SDK surface is final either way.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from dataclasses import dataclass, field
12
+ from typing import Any
13
+
14
+ from ._http import request
15
+ from .errors import DeployTimeoutError
16
+
17
+ _POLL_TIMEOUT_S = 300.0
18
+ _POLL_BASE_S = 1.0
19
+ _POLL_MAX_S = 8.0
20
+
21
+
22
+ @dataclass
23
+ class GymHandle:
24
+ """A deployed (or deploying) cloud gym session."""
25
+
26
+ gym_id: str
27
+ status: str # provisioning | ready | idle | terminated
28
+ url: str | None = None
29
+ viewer_url: str | None = None
30
+ control_token: str | None = field(default=None, repr=False)
31
+ expires_at: str | None = None
32
+
33
+ @staticmethod
34
+ def _from_api(d: dict[str, Any]) -> GymHandle:
35
+ return GymHandle(
36
+ gym_id=d["gym_id"],
37
+ status=d.get("status", "provisioning"),
38
+ url=d.get("url"),
39
+ viewer_url=d.get("viewer_url"),
40
+ control_token=d.get("control_token"),
41
+ expires_at=d.get("expires_at"),
42
+ )
43
+
44
+ def refresh(self) -> GymHandle:
45
+ payload = request("GET", f"/api/v1/gyms/{self.gym_id}")
46
+ fresh = GymHandle._from_api(payload["gym"])
47
+ self.__dict__.update(fresh.__dict__)
48
+ return self
49
+
50
+ def wait_ready(self, timeout: float = _POLL_TIMEOUT_S) -> GymHandle:
51
+ """Poll until ready (exponential backoff), or raise DeployTimeoutError."""
52
+ deadline = time.monotonic() + timeout
53
+ delay = _POLL_BASE_S
54
+ while self.status != "ready":
55
+ if time.monotonic() > deadline:
56
+ raise DeployTimeoutError(
57
+ f"gym {self.gym_id} not ready after {timeout:.0f}s "
58
+ f"(status: {self.status})",
59
+ fixes=[
60
+ "gym.refresh() later — provisioning may still finish",
61
+ "gym.logs() shows the session process output",
62
+ "gym.close() releases the slot if you are giving up",
63
+ ],
64
+ )
65
+ time.sleep(delay)
66
+ delay = min(delay * 1.7, _POLL_MAX_S)
67
+ self.refresh()
68
+ return self
69
+
70
+ def connect(self, **kw):
71
+ """→ ``world_engine_client.RemoteEnv`` driving this gym."""
72
+ self.wait_ready()
73
+ import world_engine_client as we_client
74
+
75
+ return we_client.connect(self.control_token, url=self.url, **kw)
76
+
77
+ def extend(self, minutes: int) -> None:
78
+ request("POST", f"/api/v1/gyms/{self.gym_id}/extend", body={"minutes": minutes})
79
+
80
+ def logs(self, tail: int = 100) -> str:
81
+ payload = request("GET", f"/api/v1/gyms/{self.gym_id}/logs", query={"tail": str(tail)})
82
+ return payload.get("logs", "")
83
+
84
+ def close(self) -> None:
85
+ request("DELETE", f"/api/v1/gyms/{self.gym_id}")
86
+ self.status = "terminated"
87
+
88
+ def __enter__(self) -> GymHandle:
89
+ return self
90
+
91
+ def __exit__(self, *exc: object) -> None:
92
+ self.close()
93
+
94
+
95
+ def deploy(
96
+ scene: str,
97
+ *,
98
+ task: str | None = None,
99
+ tier: str = "auto",
100
+ region: str | None = None,
101
+ ) -> GymHandle:
102
+ """Deploy a scene as a cloud gym session and return its handle."""
103
+ payload = request(
104
+ "POST",
105
+ "/api/v1/gyms",
106
+ body={"scene_id": scene, "task_id": task, "tier": tier, "region": region},
107
+ )
108
+ return GymHandle._from_api(payload["gym"])
109
+
110
+
111
+ def list_gyms() -> list[GymHandle]:
112
+ """Your active gym sessions."""
113
+ payload = request("GET", "/api/v1/gyms")
114
+ return [GymHandle._from_api(g) for g in payload.get("gyms", [])]
@@ -0,0 +1,88 @@
1
+ """Scene gallery: list / get / create / fork.
2
+
3
+ Scene ids are namespaced ``{owner}/{slug}`` (owner is the stable account
4
+ UUID). There is deliberately no upload()/download() — scene content never
5
+ transits the user's machine (product decision 2026-08-02); content is authored
6
+ in the platform-hosted browser editor, and public scenes are used via
7
+ ``fork()`` + ``deploy()``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+
15
+ from ._http import request
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Scene:
20
+ """One gallery entry (the ``/api/v1/scenes`` wire shape, typed)."""
21
+
22
+ id: str # "{owner}/{slug}"
23
+ owner: str
24
+ owner_name: str | None
25
+ slug: str
26
+ name: str
27
+ description: str
28
+ public: bool
29
+ created_at: str
30
+ updated_at: str
31
+
32
+ @staticmethod
33
+ def _from_api(d: dict[str, Any]) -> Scene:
34
+ return Scene(
35
+ id=d["id"],
36
+ owner=d["owner"],
37
+ owner_name=d.get("owner_name"),
38
+ slug=d["slug"],
39
+ name=d["name"],
40
+ description=d.get("description", ""),
41
+ public=bool(d.get("public", False)),
42
+ created_at=d.get("created_at", ""),
43
+ updated_at=d.get("updated_at", ""),
44
+ )
45
+
46
+ def fork(self) -> Scene:
47
+ """Copy this scene into your own namespace (platform-side copy)."""
48
+ owner, slug = self.id.split("/", 1)
49
+ payload = request("POST", f"/api/v1/scenes/{owner}/{slug}/fork")
50
+ return Scene._from_api(payload["scene"])
51
+
52
+
53
+ def list( # noqa: A001 - mirrors the documented da.scenes.list() surface
54
+ query: str | None = None,
55
+ *,
56
+ public: bool = True,
57
+ ) -> list[Scene]:
58
+ """Search scenes. ``public=False`` lists YOUR scenes (needs an API key)."""
59
+ payload = request(
60
+ "GET",
61
+ "/api/v1/scenes",
62
+ query={"query": query, "public": "false" if not public else None},
63
+ auth=not public,
64
+ )
65
+ return [Scene._from_api(s) for s in payload["scenes"]]
66
+
67
+
68
+ def get(scene_id: str) -> Scene:
69
+ """Fetch one scene by ``{owner}/{slug}``. Private scenes need your key."""
70
+ owner, _, slug = scene_id.partition("/")
71
+ from .config import api_key
72
+
73
+ payload = request(
74
+ "GET", f"/api/v1/scenes/{owner}/{slug}", auth=api_key() is not None
75
+ )
76
+ return Scene._from_api(payload["scene"])
77
+
78
+
79
+ def create(
80
+ slug: str, *, name: str | None = None, description: str = "", public: bool = False
81
+ ) -> Scene:
82
+ """Create scene METADATA (content is authored in the browser editor)."""
83
+ payload = request(
84
+ "POST",
85
+ "/api/v1/scenes",
86
+ body={"slug": slug, "name": name or slug, "description": description, "public": public},
87
+ )
88
+ return Scene._from_api(payload["scene"])
@@ -0,0 +1,12 @@
1
+ """Account usage / quota."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ._http import request
8
+
9
+
10
+ def usage() -> dict[str, Any]:
11
+ """This month's compute usage + quota for your account."""
12
+ return request("GET", "/api/v1/usage")["usage"]
@@ -0,0 +1,164 @@
1
+ """SDK contract tests against a local stub control plane (stdlib only).
2
+
3
+ The stub speaks the frozen /api/v1 wire shapes (07 文档 §4): {ok:true,...} /
4
+ {ok:false, code, error, fixes:[]}. These tests pin the SDK's request shapes,
5
+ auth header, error mapping, and credential resolution — no real platform needed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import threading
12
+ from http.server import BaseHTTPRequestHandler, HTTPServer
13
+
14
+ import pytest
15
+
16
+ import digiarena as da
17
+ from digiarena import errors
18
+
19
+ KEY = "da_live_test123"
20
+
21
+
22
+ class _Stub(BaseHTTPRequestHandler):
23
+ calls: list[tuple[str, str, dict | None, str | None]] = []
24
+
25
+ def _reply(self, status: int, payload: dict) -> None:
26
+ body = json.dumps(payload).encode()
27
+ self.send_response(status)
28
+ self.send_header("Content-Type", "application/json")
29
+ self.send_header("Content-Length", str(len(body)))
30
+ self.end_headers()
31
+ self.wfile.write(body)
32
+
33
+ def _record(self) -> tuple[dict | None, str | None]:
34
+ length = int(self.headers.get("Content-Length") or 0)
35
+ body = json.loads(self.rfile.read(length)) if length else None
36
+ auth = self.headers.get("Authorization")
37
+ _Stub.calls.append((self.command, self.path, body, auth))
38
+ return body, auth
39
+
40
+ def do_GET(self): # noqa: N802
41
+ _, auth = self._record()
42
+ path = self.path.split("?")[0]
43
+ if path == "/api/v1/benchmarks":
44
+ self._reply(200, {"ok": True, "benchmarks": [{"id": "tabletop-v1"}]})
45
+ elif path == "/api/v1/usage":
46
+ if auth != f"Bearer {KEY}":
47
+ self._reply(401, {"ok": False, "code": "unauthorized",
48
+ "error": "bad key", "fixes": ["create a key"]})
49
+ else:
50
+ self._reply(200, {"ok": True, "usage": {"sim_minutes_used": 0}})
51
+ elif path.startswith("/api/v1/scenes/"):
52
+ self._reply(200, {"ok": True, "scene": _SCENE})
53
+ elif path == "/api/v1/scenes":
54
+ self._reply(200, {"ok": True, "scenes": [_SCENE]})
55
+ elif path.startswith("/api/v1/gyms/"):
56
+ self._reply(200, {"ok": True, "gym": {"gym_id": "g1", "status": "ready",
57
+ "url": "http://x", "control_token": "t"}})
58
+ else:
59
+ self._reply(404, {"ok": False, "code": "not_found", "error": path, "fixes": []})
60
+
61
+ def do_POST(self): # noqa: N802
62
+ self._record()
63
+ path = self.path.split("?")[0]
64
+ if path == "/api/v1/gyms":
65
+ self._reply(501, {"ok": False, "code": "not_implemented",
66
+ "error": "gym deploy 尚未开放",
67
+ "fixes": ["该端点属于后续 milestone"]})
68
+ elif path == "/api/v1/scenes":
69
+ self._reply(200, {"ok": True, "scene": _SCENE})
70
+ else:
71
+ self._reply(404, {"ok": False, "code": "not_found", "error": path, "fixes": []})
72
+
73
+ def log_message(self, *a): # silence
74
+ pass
75
+
76
+
77
+ _SCENE = {
78
+ "id": "u1/kitchen_001", "owner": "u1", "owner_name": "alice",
79
+ "slug": "kitchen_001", "name": "Kitchen 001", "description": "",
80
+ "public": True, "created_at": "2026-01-01T00:00:00Z",
81
+ "updated_at": "2026-01-01T00:00:00Z",
82
+ }
83
+
84
+
85
+ @pytest.fixture(autouse=True)
86
+ def stub_api(monkeypatch):
87
+ server = HTTPServer(("127.0.0.1", 0), _Stub)
88
+ threading.Thread(target=server.serve_forever, daemon=True).start()
89
+ _Stub.calls = []
90
+ monkeypatch.setenv("DIGIARENA_API_URL", f"http://127.0.0.1:{server.server_port}")
91
+ monkeypatch.setenv("DIGIARENA_API_KEY", KEY)
92
+ yield server
93
+ server.shutdown()
94
+
95
+
96
+ def test_scenes_list_and_get():
97
+ scenes = da.scenes.list(query="kitchen")
98
+ assert scenes[0].id == "u1/kitchen_001"
99
+ assert scenes[0].public is True
100
+ s = da.scenes.get("u1/kitchen_001")
101
+ assert s.name == "Kitchen 001"
102
+ # list(public=True) 不带 Authorization(公开面);get 带(可见 private)
103
+ list_call = next(c for c in _Stub.calls if c[1].startswith("/api/v1/scenes?"))
104
+ assert list_call[3] is None
105
+ get_call = next(c for c in _Stub.calls if c[1] == "/api/v1/scenes/u1/kitchen_001")
106
+ assert get_call[3] == f"Bearer {KEY}"
107
+
108
+
109
+ def test_usage_sends_bearer_key():
110
+ assert da.usage() == {"sim_minutes_used": 0}
111
+ assert _Stub.calls[-1][3] == f"Bearer {KEY}"
112
+
113
+
114
+ def test_deploy_not_implemented_maps_to_typed_error():
115
+ with pytest.raises(errors.NotImplementedYetError) as ei:
116
+ da.deploy(scene="u1/kitchen_001")
117
+ assert "Possible fixes" in str(ei.value)
118
+ assert ei.value.status == 501
119
+ # 请求体形状(冻结面)
120
+ call = next(c for c in _Stub.calls if c[1] == "/api/v1/gyms")
121
+ assert call[2] == {"scene_id": "u1/kitchen_001", "task_id": None,
122
+ "tier": "auto", "region": None}
123
+
124
+
125
+ def test_unauthorized_maps_to_auth_error(monkeypatch):
126
+ monkeypatch.setenv("DIGIARENA_API_KEY", "da_live_wrong")
127
+ with pytest.raises(errors.AuthError):
128
+ da.usage()
129
+
130
+
131
+ def test_missing_key_raises_before_network(monkeypatch, tmp_path):
132
+ monkeypatch.delenv("DIGIARENA_API_KEY", raising=False)
133
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) # empty credentials
134
+ with pytest.raises(errors.AuthError) as ei:
135
+ da.usage()
136
+ assert "digiarena login" in str(ei.value)
137
+
138
+
139
+ def test_login_saves_credentials(monkeypatch, tmp_path, capsys):
140
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
141
+ monkeypatch.delenv("DIGIARENA_API_KEY", raising=False)
142
+ # config 模块在 import 时解析了路径,重新加载让 XDG 生效
143
+ import importlib
144
+
145
+ from digiarena import config as cfg
146
+ importlib.reload(cfg)
147
+ cfg.login(key="da_live_saved")
148
+ assert cfg.api_key() == "da_live_saved"
149
+ cred = tmp_path / "digiarena" / "credentials"
150
+ assert cred.is_file()
151
+ assert (cred.stat().st_mode & 0o777) == 0o600
152
+
153
+
154
+ def test_benchmarks_public_no_auth():
155
+ assert da.benchmarks.list() == [{"id": "tabletop-v1"}]
156
+ assert _Stub.calls[-1][3] is None
157
+
158
+
159
+ def test_gym_handle_context_manager():
160
+ g = da.GymHandle(gym_id="g1", status="ready", url="http://x", control_token="t")
161
+ with pytest.raises(errors.ApiError):
162
+ # DELETE /api/v1/gyms/g1 → stub 404 → typed error(形状即契约)
163
+ with g:
164
+ pass