zeno-local 0.1.3__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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: zeno-local
3
+ Version: 0.1.3
4
+ Summary: Local companion daemon that exposes your installed humex to the zeno cloud UI (zeno's ?mode=local).
5
+ Author: The Zeroth Law
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://zerothlaw.io
8
+ Keywords: zeno,humex,autonomous-vehicle,scenario,metrics
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: humex>=0.2.2
13
+ Requires-Dist: click>=8
14
+ Dynamic: license-file
15
+
16
+ # zeno-local
17
+
18
+ A small local companion daemon for the **zeno** cloud UI. It imports the
19
+ **humex** library you've installed and exposes it over a loopback HTTP server
20
+ (the Zeno Compute Protocol) so the cloud-hosted zeno SPA can run
21
+ simulate / evaluate / import / export against *your* local humex — including any
22
+ custom monitors, operators, or converters you've installed.
23
+
24
+ `humex` stays a pure library (it does not serve). `zeno-local` is the process
25
+ that owns the server.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install zeno-local # installs into the same env as your humex
31
+ ```
32
+
33
+ `humex` is a dependency, so it comes along — but if you want to use *your own*
34
+ (modified / customized) humex, install it in the same environment first, or
35
+ `pip install -e` your humex checkout there.
36
+
37
+ ## Run
38
+
39
+ Quick start from a checkout (sets up a venv, installs zeno-local + humex, runs):
40
+
41
+ ```bash
42
+ scripts/start.sh # http://127.0.0.1:8900
43
+ PORT=9100 scripts/start.sh # different port
44
+ VENV=../zeno/.venv scripts/start.sh # reuse an existing venv (and its converters)
45
+ ```
46
+
47
+ Or run the installed CLI directly:
48
+
49
+ ```bash
50
+ zeno-local # http://127.0.0.1:8900
51
+ zeno-local --port 9100 --cors-origin https://zeno.dev.zerothlaw.io
52
+ ```
53
+
54
+ Then open zeno with `?mode=local` (and `?localUrl=` if you changed the
55
+ host/port). zeno's "compute source" selector will route everything through this
56
+ server instead of the in-browser Pyodide runtime.
57
+
58
+ ## Browser support
59
+
60
+ An HTTPS-deployed zeno reaching `http://localhost` works in **Chrome** and
61
+ **Firefox** (loopback mixed-content exemption + Chrome Private Network Access
62
+ headers are handled). **Safari blocks it** — use Chrome/Firefox, or run zeno over
63
+ `http://localhost` too.
64
+
65
+ ## Endpoints (Zeno Compute Protocol, v1)
66
+
67
+ `GET /health` · `POST /parse-yaml` · `POST /test-dag` · `POST /import-package`
68
+ (raw `.hpkg` bytes) · `POST /run-simulation` · `POST /evaluate-metrics` ·
69
+ `POST /build-hpkg`. Per-tab state is keyed by the `X-Humex-Session` header.
70
+
71
+ > Roadmap: filesystem endpoints (`/fs/*`) and converter endpoints
72
+ > (`/converters`, `/convert`) so the UI can browse local dataset directories,
73
+ > run native converters, and write outputs back to disk — the capabilities the
74
+ > in-browser runtime fundamentally can't provide.
@@ -0,0 +1,59 @@
1
+ # zeno-local
2
+
3
+ A small local companion daemon for the **zeno** cloud UI. It imports the
4
+ **humex** library you've installed and exposes it over a loopback HTTP server
5
+ (the Zeno Compute Protocol) so the cloud-hosted zeno SPA can run
6
+ simulate / evaluate / import / export against *your* local humex — including any
7
+ custom monitors, operators, or converters you've installed.
8
+
9
+ `humex` stays a pure library (it does not serve). `zeno-local` is the process
10
+ that owns the server.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ pip install zeno-local # installs into the same env as your humex
16
+ ```
17
+
18
+ `humex` is a dependency, so it comes along — but if you want to use *your own*
19
+ (modified / customized) humex, install it in the same environment first, or
20
+ `pip install -e` your humex checkout there.
21
+
22
+ ## Run
23
+
24
+ Quick start from a checkout (sets up a venv, installs zeno-local + humex, runs):
25
+
26
+ ```bash
27
+ scripts/start.sh # http://127.0.0.1:8900
28
+ PORT=9100 scripts/start.sh # different port
29
+ VENV=../zeno/.venv scripts/start.sh # reuse an existing venv (and its converters)
30
+ ```
31
+
32
+ Or run the installed CLI directly:
33
+
34
+ ```bash
35
+ zeno-local # http://127.0.0.1:8900
36
+ zeno-local --port 9100 --cors-origin https://zeno.dev.zerothlaw.io
37
+ ```
38
+
39
+ Then open zeno with `?mode=local` (and `?localUrl=` if you changed the
40
+ host/port). zeno's "compute source" selector will route everything through this
41
+ server instead of the in-browser Pyodide runtime.
42
+
43
+ ## Browser support
44
+
45
+ An HTTPS-deployed zeno reaching `http://localhost` works in **Chrome** and
46
+ **Firefox** (loopback mixed-content exemption + Chrome Private Network Access
47
+ headers are handled). **Safari blocks it** — use Chrome/Firefox, or run zeno over
48
+ `http://localhost` too.
49
+
50
+ ## Endpoints (Zeno Compute Protocol, v1)
51
+
52
+ `GET /health` · `POST /parse-yaml` · `POST /test-dag` · `POST /import-package`
53
+ (raw `.hpkg` bytes) · `POST /run-simulation` · `POST /evaluate-metrics` ·
54
+ `POST /build-hpkg`. Per-tab state is keyed by the `X-Humex-Session` header.
55
+
56
+ > Roadmap: filesystem endpoints (`/fs/*`) and converter endpoints
57
+ > (`/converters`, `/convert`) so the UI can browse local dataset directories,
58
+ > run native converters, and write outputs back to disk — the capabilities the
59
+ > in-browser runtime fundamentally can't provide.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=80", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "zeno-local"
7
+ version = "0.1.3"
8
+ description = "Local companion daemon that exposes your installed humex to the zeno cloud UI (zeno's ?mode=local)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "The Zeroth Law" }]
14
+ keywords = ["zeno", "humex", "autonomous-vehicle", "scenario", "metrics"]
15
+
16
+ # humex is a hard dependency: zeno-local imports the user's installed humex and
17
+ # exposes it. Pin the floor to the release that ships the .hpkg pack/unpack API
18
+ # (humex.converters.hpkg) this server relies on.
19
+ dependencies = [
20
+ "humex>=0.2.2",
21
+ "click>=8",
22
+ ]
23
+
24
+ [project.scripts]
25
+ zeno-local = "zeno_local.cli:main"
26
+
27
+ [project.urls]
28
+ Homepage = "https://zerothlaw.io"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,16 @@
1
+ """zeno-local — a thin local companion daemon for the zeno cloud UI.
2
+
3
+ It imports the user's installed ``humex`` library and exposes it over a loopback
4
+ HTTP server (the Zeno Compute Protocol) so the cloud-hosted zeno SPA can run
5
+ simulate / evaluate / convert against the user's *local* humex — including any
6
+ custom monitors, operators, or converters they've installed.
7
+
8
+ humex stays a pure library (it does not serve); zeno-local is the process that
9
+ owns the server. Point zeno at it with ``?mode=local``.
10
+ """
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ from .app import DEFAULT_HOST, DEFAULT_PORT, run_server
15
+
16
+ __all__ = ["run_server", "DEFAULT_HOST", "DEFAULT_PORT", "__version__"]
@@ -0,0 +1,245 @@
1
+ """Loopback HTTP server for zeno's ``local`` runtime mode (Zeno Compute Protocol).
2
+
3
+ A dependency-light (stdlib :mod:`http.server`) JSON API that lets the zeno
4
+ frontend — including one deployed over HTTPS (e.g. zeno.dev.zerothlaw.io) — run
5
+ ``simulate`` / ``evaluate`` / ``import`` / ``export`` against the user's *local*
6
+ ``humex`` install. humex is imported as a plain library; this server owns all the
7
+ HTTP concerns so humex never has to.
8
+
9
+ Cross-origin notes (why this server is careful about headers):
10
+ * An HTTPS page fetching ``http://localhost`` is normally blocked as mixed
11
+ content, but Chrome/Firefox exempt loopback. Safari does NOT — Safari users
12
+ on an HTTPS site can't reach a plain-HTTP local server.
13
+ * Chrome's Private Network Access sends a CORS *preflight* for requests from a
14
+ public site to a loopback address and requires
15
+ ``Access-Control-Allow-Private-Network: true`` on the response.
16
+ Both are handled below.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import base64
22
+ import json
23
+ import threading
24
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
25
+ from typing import Dict, Optional
26
+ from urllib.parse import urlparse
27
+
28
+ import humex
29
+
30
+ from .operations import Session
31
+
32
+ __all__ = ["run_server", "DEFAULT_PORT", "DEFAULT_HOST"]
33
+
34
+ DEFAULT_PORT = 8900
35
+ DEFAULT_HOST = "127.0.0.1"
36
+
37
+ _SESSION_HEADER = "X-Humex-Session"
38
+ _DEFAULT_SESSION = "_default"
39
+
40
+ # humex APIs reachable through this server (capability handshake).
41
+ _AVAILABLE_APIS = ["ComputeDagMetricsAPI", "RunSimulationAPI", "TestDagMetricsAPI"]
42
+
43
+
44
+ def _server_version() -> str:
45
+ try:
46
+ from importlib.metadata import version
47
+
48
+ return version("zeno-local")
49
+ except Exception: # noqa: BLE001 — running from source / not installed
50
+ return "0.0.0+dev"
51
+
52
+
53
+ class _SessionRegistry:
54
+ """Thread-safe map of session-id -> :class:`Session`."""
55
+
56
+ def __init__(self) -> None:
57
+ self._sessions: Dict[str, Session] = {}
58
+ self._lock = threading.Lock()
59
+
60
+ def get(self, sid: Optional[str]) -> Session:
61
+ key = sid or _DEFAULT_SESSION
62
+ with self._lock:
63
+ sess = self._sessions.get(key)
64
+ if sess is None:
65
+ sess = Session()
66
+ self._sessions[key] = sess
67
+ return sess
68
+
69
+
70
+ def _make_handler(allow_origin: str) -> type:
71
+ registry = _SessionRegistry()
72
+ zl_version = _server_version()
73
+
74
+ class Handler(BaseHTTPRequestHandler):
75
+ server_version = f"zeno-local/{zl_version}"
76
+
77
+ # -- low-level helpers --------------------------------------------
78
+ def _cors_headers(self) -> None:
79
+ origin = self.headers.get("Origin")
80
+ if allow_origin == "*":
81
+ self.send_header("Access-Control-Allow-Origin", origin or "*")
82
+ self.send_header("Vary", "Origin")
83
+ else:
84
+ self.send_header("Access-Control-Allow-Origin", allow_origin)
85
+ self.send_header("Vary", "Origin")
86
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
87
+ self.send_header(
88
+ "Access-Control-Allow-Headers",
89
+ f"Content-Type, {_SESSION_HEADER}",
90
+ )
91
+ # Chrome Private Network Access: required when a public/secure origin
92
+ # calls a loopback address.
93
+ self.send_header("Access-Control-Allow-Private-Network", "true")
94
+ self.send_header("Access-Control-Max-Age", "600")
95
+
96
+ def _send_json(self, status: int, payload: dict) -> None:
97
+ body = json.dumps(payload).encode("utf-8")
98
+ self.send_response(status)
99
+ self._cors_headers()
100
+ self.send_header("Content-Type", "application/json")
101
+ self.send_header("Content-Length", str(len(body)))
102
+ self.end_headers()
103
+ self.wfile.write(body)
104
+
105
+ def _send_bytes(self, status: int, data: bytes, content_type: str) -> None:
106
+ self.send_response(status)
107
+ self._cors_headers()
108
+ self.send_header("Content-Type", content_type)
109
+ self.send_header("Content-Length", str(len(data)))
110
+ self.end_headers()
111
+ self.wfile.write(data)
112
+
113
+ def _read_json(self) -> dict:
114
+ length = int(self.headers.get("Content-Length", 0))
115
+ if length == 0:
116
+ return {}
117
+ return json.loads(self.rfile.read(length).decode("utf-8"))
118
+
119
+ def _read_bytes(self) -> bytes:
120
+ length = int(self.headers.get("Content-Length", 0))
121
+ return self.rfile.read(length) if length else b""
122
+
123
+ def _session(self) -> Session:
124
+ return registry.get(self.headers.get(_SESSION_HEADER))
125
+
126
+ # quieter logs — one line per request, no stderr noise.
127
+ def log_message(self, fmt: str, *args) -> None: # noqa: A002
128
+ print(f"zeno-local: {self.address_string()} - {fmt % args}")
129
+
130
+ # -- HTTP verbs ----------------------------------------------------
131
+ def do_OPTIONS(self) -> None: # noqa: N802
132
+ self.send_response(204)
133
+ self._cors_headers()
134
+ self.send_header("Content-Length", "0")
135
+ self.end_headers()
136
+
137
+ def do_GET(self) -> None: # noqa: N802
138
+ path = urlparse(self.path).path
139
+ if path in ("/health", "/"):
140
+ self._send_json(
141
+ 200,
142
+ {
143
+ "status": "ok",
144
+ "server": "zeno-local",
145
+ "zeno_local_version": zl_version,
146
+ "humex_version": humex.__version__,
147
+ "available_apis": _AVAILABLE_APIS,
148
+ "cold_start_seconds": 0,
149
+ },
150
+ )
151
+ return
152
+ if path == "/converters":
153
+ self._send_json(200, self._session().list_converters())
154
+ return
155
+ self._send_json(404, {"success": False, "error": f"not found: {path}"})
156
+
157
+ def do_POST(self) -> None: # noqa: N802
158
+ path = urlparse(self.path).path
159
+ try:
160
+ self._route_post(path)
161
+ except Exception as exc: # noqa: BLE001 — never 500 silently
162
+ self._send_json(500, {"success": False, "error": str(exc)})
163
+
164
+ def _route_post(self, path: str) -> None:
165
+ session = self._session()
166
+
167
+ if path == "/parse-yaml":
168
+ body = self._read_json()
169
+ self._send_json(200, session.parse_yaml(body.get("yaml_text", "")))
170
+ return
171
+ if path == "/test-dag":
172
+ body = self._read_json()
173
+ self._send_json(200, session.test_dag(body.get("dag_yaml", "")))
174
+ return
175
+ if path == "/import-package":
176
+ # Raw .hpkg bytes in the request body (Content-Type ignored).
177
+ result = session.import_package(self._read_bytes())
178
+ self._send_json(200, {"success": True, **result})
179
+ return
180
+ if path == "/run-simulation":
181
+ body = self._read_json()
182
+ self._send_json(200, session.run_simulation(body.get("config_json", {})))
183
+ return
184
+ if path == "/evaluate-metrics":
185
+ body = self._read_json()
186
+ self._send_json(
187
+ 200,
188
+ session.evaluate_metrics(body.get("metric_yaml_content", "")),
189
+ )
190
+ return
191
+ if path == "/convert":
192
+ body = self._read_json()
193
+ self._send_json(
194
+ 200,
195
+ session.convert(
196
+ converter_name=body.get("converter") or "",
197
+ input_bytes=base64.b64decode(body.get("input_base64") or ""),
198
+ input_filename=body.get("filename") or "input",
199
+ options=body.get("options") or {},
200
+ ego_id=body.get("ego_id"),
201
+ frequency=body.get("frequency"),
202
+ ),
203
+ )
204
+ return
205
+ if path == "/build-hpkg":
206
+ body = self._read_json()
207
+ data = session.build_hpkg(
208
+ name=body.get("name") or "scenario",
209
+ config_json=body.get("config_json"),
210
+ metric_yaml=body.get("metric_yaml_content"),
211
+ have_scenario=bool(body.get("have_scenario")),
212
+ )
213
+ self._send_bytes(200, data, "application/octet-stream")
214
+ return
215
+
216
+ self._send_json(404, {"success": False, "error": f"not found: {path}"})
217
+
218
+ return Handler
219
+
220
+
221
+ def run_server(
222
+ host: str = DEFAULT_HOST,
223
+ port: int = DEFAULT_PORT,
224
+ allow_origin: str = "*",
225
+ ) -> None:
226
+ """Start the blocking local server. Ctrl-C to stop."""
227
+ handler = _make_handler(allow_origin)
228
+ httpd = ThreadingHTTPServer((host, port), handler)
229
+ origin_note = "any origin" if allow_origin == "*" else allow_origin
230
+ print(f"zeno-local {_server_version()} (humex {humex.__version__})", flush=True)
231
+ print(f" listening on http://{host}:{port}", flush=True)
232
+ print(f" CORS origin: {origin_note}", flush=True)
233
+ print(
234
+ " endpoints: /health /converters /parse-yaml /test-dag /import-package "
235
+ "/run-simulation /evaluate-metrics /convert /build-hpkg",
236
+ flush=True,
237
+ )
238
+ print(" point zeno at this server with ?mode=local", flush=True)
239
+ print(" press Ctrl-C to stop", flush=True)
240
+ try:
241
+ httpd.serve_forever()
242
+ except KeyboardInterrupt:
243
+ print("\nzeno-local: shutting down")
244
+ finally:
245
+ httpd.server_close()
@@ -0,0 +1,46 @@
1
+ """``zeno-local`` CLI — serve the user's local humex to a zeno frontend."""
2
+
3
+ import click
4
+
5
+ from .app import DEFAULT_HOST, DEFAULT_PORT, run_server
6
+
7
+
8
+ @click.command()
9
+ @click.option(
10
+ "--host",
11
+ default=DEFAULT_HOST,
12
+ show_default=True,
13
+ help="Interface to bind. Keep the loopback default unless you know why "
14
+ "you're exposing it on the network.",
15
+ )
16
+ @click.option(
17
+ "--port",
18
+ default=DEFAULT_PORT,
19
+ show_default=True,
20
+ type=int,
21
+ help="Port to listen on.",
22
+ )
23
+ @click.option(
24
+ "--cors-origin",
25
+ default="*",
26
+ show_default=True,
27
+ help="Allowed browser origin (e.g. https://zeno.dev.zerothlaw.io). "
28
+ "Default '*' echoes the request origin — convenient for local dev.",
29
+ )
30
+ def main(host: str, port: int, cors_origin: str) -> None:
31
+ """Expose your local humex to the zeno cloud UI.
32
+
33
+ Point zeno at this server with ``?mode=local`` (and ``?localUrl=`` if you
34
+ changed host/port). Works from an HTTPS-deployed zeno in Chrome and Firefox
35
+ via the loopback mixed-content exemption; Safari blocks it.
36
+
37
+ \b
38
+ Example:
39
+ zeno-local
40
+ zeno-local --port 9100 --cors-origin https://zeno.dev.zerothlaw.io
41
+ """
42
+ run_server(host=host, port=port, allow_origin=cors_origin)
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
@@ -0,0 +1,488 @@
1
+ """Stateful humex operations for the local ``humex serve`` HTTP server.
2
+
3
+ Each browser tab gets its own :class:`Session`. A session owns a temp
4
+ directory that holds the currently-loaded ``scenario.pb`` / ``map.pb`` so a
5
+ follow-up evaluate / simulate / export operates on the held bytes — exactly
6
+ the stash model zeno's Pyodide worker implements in MEMFS
7
+ (see zeno ``frontend/public/workers/pyodide.worker.js``).
8
+
9
+ This module contains zero HTTP concerns; it only turns request payloads into
10
+ JSON-serializable dicts whose shapes match the worker's replies so the zeno
11
+ ``LocalServerRuntime`` and ``BrowserRuntime`` are interchangeable.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import contextlib
18
+ import io
19
+ import json
20
+ import logging
21
+ import os
22
+ import shutil
23
+ import tempfile
24
+ import time
25
+ from pathlib import Path
26
+ from typing import Any, Dict, Iterator, List, Optional
27
+
28
+ import yaml
29
+ from google.protobuf.json_format import MessageToDict
30
+
31
+ from humex.proto import (
32
+ map_pb2,
33
+ metric_result_pb2,
34
+ scenario_pb2,
35
+ signal_pb2,
36
+ )
37
+
38
+ __all__ = ["Session"]
39
+
40
+
41
+ @contextlib.contextmanager
42
+ def _capture_into(sink: List[str]) -> Iterator[None]:
43
+ """Collect humex's output into ``sink`` while the block runs.
44
+
45
+ humex emits progress two ways: the stdlib :mod:`logging` (the converter
46
+ plugins, the enhance/lane_map/role pipeline) and plain ``print`` / rich
47
+ Console (the CLI helpers). We grab both — a logging handler appends records
48
+ live, and stdout/stderr are redirected and flushed in afterward — so the
49
+ zeno Logs panel shows exactly what ``humex convert`` would print."""
50
+
51
+ class _Handler(logging.Handler):
52
+ def emit(self, record: logging.LogRecord) -> None:
53
+ try:
54
+ sink.append(f"[{record.levelname.lower()}] {record.getMessage()}")
55
+ except Exception: # noqa: BLE001 — logging must never raise
56
+ pass
57
+
58
+ handler = _Handler()
59
+ root = logging.getLogger()
60
+ prev_level = root.level
61
+ root.addHandler(handler)
62
+ if prev_level == logging.NOTSET or prev_level > logging.INFO:
63
+ root.setLevel(logging.INFO)
64
+
65
+ out = io.StringIO()
66
+ try:
67
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
68
+ yield
69
+ finally:
70
+ root.removeHandler(handler)
71
+ root.setLevel(prev_level)
72
+ for line in out.getvalue().splitlines():
73
+ if line.strip():
74
+ sink.append(line)
75
+
76
+
77
+ def _decode(data: Optional[bytes], msg_cls) -> Optional[dict]:
78
+ """Raw protobuf bytes -> JSON dict (no field renaming; the TS transformers
79
+ own zeno-shape conversion). Returns ``None`` for absent pieces."""
80
+ if data is None:
81
+ return None
82
+ msg = msg_cls()
83
+ msg.ParseFromString(data)
84
+ return MessageToDict(msg, preserving_proto_field_name=True)
85
+
86
+
87
+ class Session:
88
+ """One client tab's runtime state.
89
+
90
+ Holds a temp dir with the loaded scenario/map bytes. Methods mirror the
91
+ worker commands one-for-one (``parseHpkg`` → :meth:`import_package`, etc.).
92
+ """
93
+
94
+ def __init__(self) -> None:
95
+ self._dir = tempfile.mkdtemp(prefix="humex-serve-")
96
+
97
+ # -- paths -------------------------------------------------------------
98
+ @property
99
+ def _scenario_path(self) -> str:
100
+ return os.path.join(self._dir, "scenario.pb")
101
+
102
+ @property
103
+ def _map_path(self) -> str:
104
+ return os.path.join(self._dir, "map.pb")
105
+
106
+ def _has_scenario(self) -> bool:
107
+ return os.path.exists(self._scenario_path)
108
+
109
+ def _has_map(self) -> bool:
110
+ return os.path.exists(self._map_path)
111
+
112
+ def close(self) -> None:
113
+ shutil.rmtree(self._dir, ignore_errors=True)
114
+
115
+ # -- stateless ops -----------------------------------------------------
116
+ def parse_yaml(self, yaml_text: str) -> Dict[str, Any]:
117
+ try:
118
+ return {"success": True, "config": yaml.safe_load(yaml_text or "")}
119
+ except Exception as exc: # noqa: BLE001 — surfaced to the UI verbatim
120
+ return {"success": False, "error": str(exc)}
121
+
122
+ def test_dag(self, dag_yaml: str) -> Dict[str, Any]:
123
+ """Quick-Test a DAG against inline ``mock_monitors`` (no scenario/map)."""
124
+ from humex.api.metrics_api import TestDagMetricsAPI
125
+
126
+ out_dir = os.path.join(self._dir, "testdag_out")
127
+ dag_path = os.path.join(self._dir, "testdag.yaml")
128
+ with open(dag_path, "w") as f:
129
+ f.write(dag_yaml or "")
130
+ try:
131
+ parsed = yaml.safe_load(dag_yaml or "") or {}
132
+ raw = parsed.get("mock_monitors", [])
133
+ mocks: Dict[str, Any] = {}
134
+ if isinstance(raw, list):
135
+ for m in raw:
136
+ mocks[m.get("name", "")] = {k: v for k, v in m.items() if k != "name"}
137
+ elif isinstance(raw, dict):
138
+ mocks = raw
139
+
140
+ res = TestDagMetricsAPI().compute(
141
+ dag_yaml_path=dag_path,
142
+ mock_monitors=mocks or None,
143
+ output_dir=out_dir,
144
+ )
145
+ path = res.get("metric_result_path")
146
+ if not path or not os.path.exists(path):
147
+ return {"success": False, "error": "test-dag produced no result"}
148
+ with open(path, "rb") as f:
149
+ mr = metric_result_pb2.MetricResult()
150
+ mr.ParseFromString(f.read())
151
+ return {
152
+ "success": True,
153
+ "metric_result_pb": MessageToDict(mr, preserving_proto_field_name=True),
154
+ "logs": res.get("logs", []),
155
+ }
156
+ except Exception as exc: # noqa: BLE001
157
+ return {"success": False, "error": str(exc)}
158
+
159
+ # -- stateful ops ------------------------------------------------------
160
+ def import_package(self, pkg_bytes: bytes) -> Dict[str, Any]:
161
+ """Unpack a ``.hpkg``; stash scenario/map; return proto-shape dicts.
162
+
163
+ Mirrors the worker's ``parseHpkg``: the archive layout is owned by
164
+ ``humex.converters.hpkg``; we only decode the bytes and compute
165
+ lane-boundary ``map_segments`` (opaque polylines to the TS side).
166
+ """
167
+ from humex.converters.hpkg import unpack_hpkg
168
+ from humex.hmap.road_map_loader import RoadMapLoader
169
+
170
+ c = unpack_hpkg(pkg_bytes)
171
+
172
+ # Stash scenario.pb so a later evaluate/export reads it without a
173
+ # re-upload; drop any stale scenario when this package has none.
174
+ if c.scenario_pb is not None:
175
+ with open(self._scenario_path, "wb") as f:
176
+ f.write(c.scenario_pb)
177
+ elif self._has_scenario():
178
+ os.remove(self._scenario_path)
179
+ if c.map_pb is not None:
180
+ with open(self._map_path, "wb") as f:
181
+ f.write(c.map_pb)
182
+
183
+ map_segments: List[List[List[float]]] = []
184
+ if c.map_pb is not None:
185
+ try:
186
+ road_map = RoadMapLoader.create_road_map(
187
+ self._map_path, map_name="hpkg_upload"
188
+ )
189
+ for seg in road_map.get_segments(centerline=False):
190
+ pts = []
191
+ for p in seg:
192
+ if isinstance(p, tuple):
193
+ pts.append([float(p[0]), float(p[1])])
194
+ else:
195
+ pts.append([float(p.x), float(p.y)])
196
+ map_segments.append(pts)
197
+ except Exception as exc: # noqa: BLE001 — non-fatal, log + continue
198
+ print(f"humex serve: get_segments failed: {exc}")
199
+
200
+ return {
201
+ "manifest": c.manifest,
202
+ "scenario_pb": _decode(c.scenario_pb, scenario_pb2.ScenarioData),
203
+ "map_pb": _decode(c.map_pb, map_pb2.Map),
204
+ "signal_pb": _decode(c.signal_pb, signal_pb2.SignalData),
205
+ "metric_result_pb": _decode(
206
+ c.metric_result_pb, metric_result_pb2.MetricResult
207
+ ),
208
+ "metric_config_yaml": c.metric_yaml,
209
+ "config_json": c.config_json,
210
+ "map_segments": map_segments,
211
+ }
212
+
213
+ def run_simulation(self, config_json: Dict[str, Any]) -> Dict[str, Any]:
214
+ """Simulate from an AVA config against the stashed map; promote the
215
+ result to the scenario stash so Evaluate/Export use it next."""
216
+ from humex.api.simulation_api import RunSimulationAPI
217
+
218
+ if not self._has_map():
219
+ return {
220
+ "success": False,
221
+ "error": 'No map loaded — use "Create from Map" before simulating.',
222
+ }
223
+ cfg_path = os.path.join(self._dir, "sim_config.json")
224
+ with open(cfg_path, "w") as f:
225
+ json.dump(config_json or {}, f)
226
+ try:
227
+ t0 = time.perf_counter()
228
+ result = RunSimulationAPI().run(
229
+ config_path=cfg_path,
230
+ map_path=self._map_path,
231
+ output_dir=os.path.join(self._dir, "sim_out"),
232
+ output_name="sim",
233
+ )
234
+ shutil.copyfile(result["scenario_proto_path"], self._scenario_path)
235
+ with open(self._scenario_path, "rb") as f:
236
+ msg = scenario_pb2.ScenarioData()
237
+ msg.ParseFromString(f.read())
238
+ return {
239
+ "success": True,
240
+ "scenario_pb": MessageToDict(msg, preserving_proto_field_name=True),
241
+ "simulation_time_seconds": result.get(
242
+ "simulation_time_seconds", time.perf_counter() - t0
243
+ ),
244
+ }
245
+ except Exception as exc: # noqa: BLE001
246
+ return {"success": False, "error": str(exc)}
247
+
248
+ def evaluate_metrics(self, metric_yaml_content: str) -> Dict[str, Any]:
249
+ """Evaluate a DAG against the stashed scenario+map (with humex logs)."""
250
+ from humex.api.metrics_api import ComputeDagMetricsAPI
251
+
252
+ logs: List[str] = []
253
+ if not self._has_scenario() or not self._has_map():
254
+ return {
255
+ "success": False,
256
+ "error": "scenario or map not loaded (import a package first)",
257
+ "logs": ["[error] no scenario/map loaded — import a package first"],
258
+ }
259
+ yaml_path = os.path.join(self._dir, "metric.yaml")
260
+ with open(yaml_path, "w") as f:
261
+ f.write(metric_yaml_content or "")
262
+ logs.append("[humex] evaluate-metrics: computing DAG against stashed scenario")
263
+ result: Any = None
264
+ error: Optional[str] = None
265
+ with _capture_into(logs):
266
+ try:
267
+ result = ComputeDagMetricsAPI().compute(
268
+ dag_yaml_path=yaml_path,
269
+ scenario_file_path=self._scenario_path,
270
+ map_file_path=self._map_path,
271
+ save_metrics_result=False,
272
+ )
273
+ except Exception as exc: # noqa: BLE001
274
+ error = str(exc)
275
+ logs.append(f"[error] {type(exc).__name__}: {exc}")
276
+ if error is not None:
277
+ return {"success": False, "error": error, "logs": logs}
278
+ mr = result.get("metric_result") if isinstance(result, dict) else None
279
+ metric_dict = (
280
+ MessageToDict(mr, preserving_proto_field_name=True)
281
+ if mr is not None
282
+ else None
283
+ )
284
+ meta = result.get("evaluation_metadata", {}) if isinstance(result, dict) else {}
285
+ logs.append("[humex] evaluate-metrics: done")
286
+ return {
287
+ "success": True,
288
+ "metric_result_pb": metric_dict,
289
+ "evaluation_metadata": meta,
290
+ "logs": logs,
291
+ }
292
+
293
+ def convert(
294
+ self,
295
+ converter_name: str,
296
+ input_bytes: bytes,
297
+ input_filename: str,
298
+ options: Optional[Dict[str, Any]] = None,
299
+ ego_id: Optional[int] = None,
300
+ frequency: Optional[float] = None,
301
+ ) -> Dict[str, Any]:
302
+ """Run a named converter over uploaded raw bytes → ``.hpkg``.
303
+
304
+ Mirrors ``humex convert`` (registry lookup → ``converter.convert`` →
305
+ enhance/lane_map/role pipeline → ``package_as_hpkg``) but stays in a
306
+ per-call temp dir and returns the archive as base64 plus the humex log
307
+ lines, so the zeno UI can show output and stash the result."""
308
+ from humex.converters.registry import converters as _registry
309
+
310
+ cls = _registry().get(converter_name)
311
+ if cls is None:
312
+ installed = ", ".join(sorted(_registry())) or "(none)"
313
+ return {
314
+ "success": False,
315
+ "error": f"converter '{converter_name}' not installed",
316
+ "logs": [
317
+ f"[error] converter '{converter_name}' is not installed in this "
318
+ f"humex (installed: {installed})"
319
+ ],
320
+ }
321
+
322
+ from humex.convert import run_pipeline
323
+ from humex.converters.hpkg_packager import (
324
+ load_meta_for_manifest,
325
+ package_as_hpkg,
326
+ )
327
+
328
+ work = Path(tempfile.mkdtemp(prefix="zl-convert-", dir=self._dir))
329
+ in_name = os.path.basename(input_filename) or "input"
330
+ in_path = work / in_name
331
+ in_path.write_bytes(input_bytes)
332
+ out_dir = work / "out"
333
+
334
+ logs: List[str] = [f"[humex] convert {in_name} → {converter_name}"]
335
+ hpkg_bytes: Optional[bytes] = None
336
+ error: Optional[str] = None
337
+
338
+ # Enhancement: ego_id is a converter-stage option — pass it only to
339
+ # converters whose convert() accepts it (e.g. Waymo), else note + skip.
340
+ conv_opts = dict(options or {})
341
+ if ego_id is not None:
342
+ import inspect
343
+
344
+ params = inspect.signature(cls.convert).parameters
345
+ if "ego_id" in params or any(
346
+ p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()
347
+ ):
348
+ conv_opts["ego_id"] = int(ego_id)
349
+ else:
350
+ logs.append(
351
+ f"[warning] converter '{converter_name}' has no ego_id option "
352
+ f"— ignoring ego id {ego_id}"
353
+ )
354
+
355
+ with _capture_into(logs):
356
+ try:
357
+ result = cls(str(in_path)).convert(output_dir=str(out_dir), **conv_opts)
358
+ episode_dir = (
359
+ Path(result.scenario_path).parent if result.scenario_path else None
360
+ )
361
+ if episode_dir is None:
362
+ raise RuntimeError("converter produced no scenario")
363
+ # Stages 2-4 (enhance / lane_map / role) — best-effort, as in the CLI.
364
+ try:
365
+ pipeline_result = run_pipeline(episode_dir, force=True)
366
+ for line in pipeline_result.summary_lines():
367
+ logs.append(f"[humex] {line}")
368
+ except Exception as exc: # noqa: BLE001
369
+ logs.append(f"[warning] enhance/lane_map/role pipeline failed: {exc}")
370
+
371
+ # Enhancement: resample to the requested frequency (Hz). humex's
372
+ # ScenarioAPI does linear-interp resample + re-enhance; write the
373
+ # result back to scenario.pb so the packaged .hpkg uses it.
374
+ if frequency:
375
+ try:
376
+ from humex.api import ScenarioAPI
377
+
378
+ scen_path = Path(result.scenario_path)
379
+ api = ScenarioAPI()
380
+ scen = api.load_from_proto_files(
381
+ str(scen_path),
382
+ str(episode_dir / "map.pb"),
383
+ enhance=True,
384
+ frequency=float(frequency),
385
+ )
386
+ scen_path.write_bytes(
387
+ api.scenario_to_proto(scen).SerializeToString()
388
+ )
389
+ logs.append(f"[humex] resampled to {frequency} Hz")
390
+ except Exception as exc: # noqa: BLE001
391
+ logs.append(f"[warning] resample to {frequency} Hz failed: {exc}")
392
+ hpkg_path = work / f"{episode_dir.name}.hpkg"
393
+ package_as_hpkg(
394
+ episode_dir,
395
+ hpkg_path,
396
+ name=episode_dir.name,
397
+ source={"converter": converter_name, "input_file": in_name},
398
+ scenario_metadata=load_meta_for_manifest(episode_dir),
399
+ )
400
+ hpkg_bytes = hpkg_path.read_bytes()
401
+ except Exception as exc: # noqa: BLE001
402
+ error = f"{type(exc).__name__}: {exc}"
403
+ logs.append(f"[error] {error}")
404
+
405
+ if hpkg_bytes is None:
406
+ return {"success": False, "error": error or "conversion failed", "logs": logs}
407
+
408
+ stem = in_name.rsplit(".", 1)[0] if "." in in_name else in_name
409
+ logs.append(f"[humex] packed {stem}.hpkg ({len(hpkg_bytes)} bytes)")
410
+ return {
411
+ "success": True,
412
+ "name": f"{stem}.hpkg",
413
+ # On-disk locations on the machine running zeno-local: the packed
414
+ # .hpkg and the converter's output folder. The zeno UI shows these
415
+ # in the Details panel. (Browser/cloud conversions have no path.)
416
+ "path": str(hpkg_path),
417
+ "folder": str(episode_dir),
418
+ "hpkg_base64": base64.b64encode(hpkg_bytes).decode("ascii"),
419
+ "logs": logs,
420
+ }
421
+
422
+ def build_hpkg(
423
+ self,
424
+ name: str,
425
+ config_json: Optional[dict],
426
+ metric_yaml: Optional[str],
427
+ have_scenario: bool,
428
+ ) -> bytes:
429
+ """Pack a ``.hpkg`` from the stashed map (+ optional scenario/config/
430
+ metric yaml). Raises if no map is loaded."""
431
+ from humex.converters.hpkg import pack_hpkg
432
+
433
+ if not self._has_map():
434
+ raise RuntimeError(
435
+ "No map is loaded — re-import a package before exporting."
436
+ )
437
+ with open(self._map_path, "rb") as f:
438
+ map_pb = f.read()
439
+ scenario_pb = None
440
+ if have_scenario and self._has_scenario():
441
+ with open(self._scenario_path, "rb") as f:
442
+ scenario_pb = f.read()
443
+ return pack_hpkg(
444
+ name=name or "scenario",
445
+ scenario_pb=scenario_pb,
446
+ map_pb=map_pb,
447
+ config_json=config_json,
448
+ metric_yaml=metric_yaml,
449
+ source="zeno",
450
+ )
451
+
452
+ # -- discovery (stateless) --------------------------------------------
453
+ def list_converters(self) -> Dict[str, Any]:
454
+ """Enumerate the converter plugins installed in *this* humex env.
455
+
456
+ Mirrors ``humex plugins``: walks the ``humex.converters`` entry-point
457
+ registry and pairs each with its distribution + declared extensions, so
458
+ the zeno Compute UI can list the user's local converters (including any
459
+ custom ones they've pip-installed alongside their humex)."""
460
+ from importlib.metadata import distributions
461
+
462
+ from humex.converters.registry import ENTRY_POINT_GROUP, converters
463
+
464
+ pkg_index: Dict[str, tuple] = {}
465
+ for dist in distributions():
466
+ try:
467
+ eps = dist.entry_points
468
+ except Exception: # noqa: BLE001
469
+ continue
470
+ for ep in eps:
471
+ if ep.group == ENTRY_POINT_GROUP:
472
+ pkg_index[ep.name] = (dist.name or "?", dist.version or "?")
473
+
474
+ out: List[Dict[str, Any]] = []
475
+ for name, cls in converters().items():
476
+ pkg, ver = pkg_index.get(name, ("?", "?"))
477
+ doc = (cls.__doc__ or "").strip().splitlines()
478
+ out.append(
479
+ {
480
+ "name": name,
481
+ "class_name": f"{cls.__module__}.{cls.__qualname__}",
482
+ "package": pkg,
483
+ "version": ver,
484
+ "extensions": list(getattr(cls, "EXTENSIONS", ()) or ()),
485
+ "description": doc[0].strip() if doc else "",
486
+ }
487
+ )
488
+ return {"converters": out}
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: zeno-local
3
+ Version: 0.1.3
4
+ Summary: Local companion daemon that exposes your installed humex to the zeno cloud UI (zeno's ?mode=local).
5
+ Author: The Zeroth Law
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://zerothlaw.io
8
+ Keywords: zeno,humex,autonomous-vehicle,scenario,metrics
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: humex>=0.2.2
13
+ Requires-Dist: click>=8
14
+ Dynamic: license-file
15
+
16
+ # zeno-local
17
+
18
+ A small local companion daemon for the **zeno** cloud UI. It imports the
19
+ **humex** library you've installed and exposes it over a loopback HTTP server
20
+ (the Zeno Compute Protocol) so the cloud-hosted zeno SPA can run
21
+ simulate / evaluate / import / export against *your* local humex — including any
22
+ custom monitors, operators, or converters you've installed.
23
+
24
+ `humex` stays a pure library (it does not serve). `zeno-local` is the process
25
+ that owns the server.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install zeno-local # installs into the same env as your humex
31
+ ```
32
+
33
+ `humex` is a dependency, so it comes along — but if you want to use *your own*
34
+ (modified / customized) humex, install it in the same environment first, or
35
+ `pip install -e` your humex checkout there.
36
+
37
+ ## Run
38
+
39
+ Quick start from a checkout (sets up a venv, installs zeno-local + humex, runs):
40
+
41
+ ```bash
42
+ scripts/start.sh # http://127.0.0.1:8900
43
+ PORT=9100 scripts/start.sh # different port
44
+ VENV=../zeno/.venv scripts/start.sh # reuse an existing venv (and its converters)
45
+ ```
46
+
47
+ Or run the installed CLI directly:
48
+
49
+ ```bash
50
+ zeno-local # http://127.0.0.1:8900
51
+ zeno-local --port 9100 --cors-origin https://zeno.dev.zerothlaw.io
52
+ ```
53
+
54
+ Then open zeno with `?mode=local` (and `?localUrl=` if you changed the
55
+ host/port). zeno's "compute source" selector will route everything through this
56
+ server instead of the in-browser Pyodide runtime.
57
+
58
+ ## Browser support
59
+
60
+ An HTTPS-deployed zeno reaching `http://localhost` works in **Chrome** and
61
+ **Firefox** (loopback mixed-content exemption + Chrome Private Network Access
62
+ headers are handled). **Safari blocks it** — use Chrome/Firefox, or run zeno over
63
+ `http://localhost` too.
64
+
65
+ ## Endpoints (Zeno Compute Protocol, v1)
66
+
67
+ `GET /health` · `POST /parse-yaml` · `POST /test-dag` · `POST /import-package`
68
+ (raw `.hpkg` bytes) · `POST /run-simulation` · `POST /evaluate-metrics` ·
69
+ `POST /build-hpkg`. Per-tab state is keyed by the `X-Humex-Session` header.
70
+
71
+ > Roadmap: filesystem endpoints (`/fs/*`) and converter endpoints
72
+ > (`/converters`, `/convert`) so the UI can browse local dataset directories,
73
+ > run native converters, and write outputs back to disk — the capabilities the
74
+ > in-browser runtime fundamentally can't provide.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/zeno_local/__init__.py
5
+ src/zeno_local/app.py
6
+ src/zeno_local/cli.py
7
+ src/zeno_local/operations.py
8
+ src/zeno_local.egg-info/PKG-INFO
9
+ src/zeno_local.egg-info/SOURCES.txt
10
+ src/zeno_local.egg-info/dependency_links.txt
11
+ src/zeno_local.egg-info/entry_points.txt
12
+ src/zeno_local.egg-info/requires.txt
13
+ src/zeno_local.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ zeno-local = zeno_local.cli:main
@@ -0,0 +1,2 @@
1
+ humex>=0.2.2
2
+ click>=8
@@ -0,0 +1 @@
1
+ zeno_local