herald-bridge 0.9.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.
Files changed (41) hide show
  1. herald_bridge-0.9.0/.gitignore +10 -0
  2. herald_bridge-0.9.0/PKG-INFO +165 -0
  3. herald_bridge-0.9.0/README.md +149 -0
  4. herald_bridge-0.9.0/herald_relay/__init__.py +13 -0
  5. herald_bridge-0.9.0/herald_relay/agent_info.py +248 -0
  6. herald_bridge-0.9.0/herald_relay/agent_info_helper.py +107 -0
  7. herald_bridge-0.9.0/herald_relay/bridge_update.py +882 -0
  8. herald_bridge-0.9.0/herald_relay/edge_tunnel.py +189 -0
  9. herald_bridge-0.9.0/herald_relay/event_classifier.py +234 -0
  10. herald_bridge-0.9.0/herald_relay/hermes_update.py +607 -0
  11. herald_bridge-0.9.0/herald_relay/local_bridge.py +54 -0
  12. herald_bridge-0.9.0/herald_relay/local_passwords.py +167 -0
  13. herald_bridge-0.9.0/herald_relay/local_screen.py +273 -0
  14. herald_bridge-0.9.0/herald_relay/local_skills.py +339 -0
  15. herald_bridge-0.9.0/herald_relay/migrate.py +286 -0
  16. herald_bridge-0.9.0/herald_relay/passwords_import.py +291 -0
  17. herald_bridge-0.9.0/herald_relay/plugin.py +231 -0
  18. herald_bridge-0.9.0/herald_relay/push_triggers.py +140 -0
  19. herald_bridge-0.9.0/herald_relay/relay_client.py +926 -0
  20. herald_bridge-0.9.0/herald_relay/screen_pipe.py +275 -0
  21. herald_bridge-0.9.0/herald_relay/tunnel_cli.py +736 -0
  22. herald_bridge-0.9.0/herald_tunnel.py +114 -0
  23. herald_bridge-0.9.0/pyproject.toml +50 -0
  24. herald_bridge-0.9.0/tests/__init__.py +0 -0
  25. herald_bridge-0.9.0/tests/test_agent_info.py +303 -0
  26. herald_bridge-0.9.0/tests/test_background_updates.py +299 -0
  27. herald_bridge-0.9.0/tests/test_bridge_update.py +591 -0
  28. herald_bridge-0.9.0/tests/test_classifier.py +131 -0
  29. herald_bridge-0.9.0/tests/test_docs_install_paths.py +45 -0
  30. herald_bridge-0.9.0/tests/test_hermes_update.py +435 -0
  31. herald_bridge-0.9.0/tests/test_local_cards_skill.py +47 -0
  32. herald_bridge-0.9.0/tests/test_local_passwords.py +162 -0
  33. herald_bridge-0.9.0/tests/test_local_screen.py +262 -0
  34. herald_bridge-0.9.0/tests/test_local_screen_passwords.py +213 -0
  35. herald_bridge-0.9.0/tests/test_migrate.py +380 -0
  36. herald_bridge-0.9.0/tests/test_plugin_registration.py +175 -0
  37. herald_bridge-0.9.0/tests/test_push_triggers.py +98 -0
  38. herald_bridge-0.9.0/tests/test_push_triggers_real_events.py +131 -0
  39. herald_bridge-0.9.0/tests/test_tunnel_keepalive.py +140 -0
  40. herald_bridge-0.9.0/tests/test_tunnel_status.py +72 -0
  41. herald_bridge-0.9.0/uv.lock +1146 -0
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ *.egg-info/
5
+ dist/
6
+ .env
7
+ node_modules/
8
+ .docusaurus/
9
+ build/
10
+ firebase-debug.log
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.5
2
+ Name: herald-bridge
3
+ Version: 0.9.0
4
+ Summary: Herald Relay plugin for Hermes — voice-first AI on mobile
5
+ Project-URL: Homepage, https://herald.app
6
+ Project-URL: Repository, https://github.com/Mohit-Ak/herald-relay
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: aiohttp>=3.10.0
9
+ Requires-Dist: cryptography>=42
10
+ Requires-Dist: httpx>=0.27.0
11
+ Requires-Dist: pyyaml>=6.0
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
14
+ Requires-Dist: pytest>=8; extra == 'dev'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # hermes-herald (Herald Bridge)
18
+
19
+ Connect your local Hermes AI agent to Herald — voice-first conversations on mobile.
20
+
21
+ Full guide: <https://heraldbridge.dev/docs/setup>.
22
+
23
+ ## Install (it keeps itself up to date)
24
+
25
+ Install into its own venv at `~/.herald-relay`, the only place Herald Bridge can
26
+ update itself. `hermes-herald` is not published on PyPI; install it from GitHub:
27
+
28
+ ```bash
29
+ python3 -m venv ~/.herald-relay
30
+ ~/.herald-relay/bin/pip install "git+https://github.com/Mohit-Ak/herald-relay#subdirectory=plugin"
31
+ ~/.herald-relay/bin/herald-tunnel setup # registers this machine, installs the service
32
+ ~/.herald-relay/bin/herald-tunnel status # local Hermes → relay → this tunnel, end to end
33
+ ```
34
+
35
+ `setup` writes the `herald:` block of `~/.hermes/config.yaml` for you:
36
+
37
+ ```yaml
38
+ herald:
39
+ relay_url: https://herald-api.eventhorizonlabs.xyz
40
+ device_token: <registered by setup>
41
+ # auto_update: false # pin this version
42
+ ```
43
+
44
+ (Older docs said `plugins.herald-relay` and `wss://relay.herald.app`. Nothing reads
45
+ that key, and that host never existed.)
46
+
47
+ **Installed somewhere else?** A bridge installed with `pip install` into Hermes' own
48
+ venv, with `pip --user`, or into any other venv moves itself into `~/.herald-relay`:
49
+ `herald-tunnel setup` does it before writing anything, and a running tunnel does it
50
+ in the background once nothing is in flight (`herald_relay/migrate.py`). It installs
51
+ the release named by the signed manifest, rewrites only the `ExecStart` line of the
52
+ systemd user unit (and the keepalive script and skills), and re-execs from there. The
53
+ device token and settings live in `~/.hermes/config.yaml`, so pairing is unchanged.
54
+ Not moved: developer checkouts (`pip install -e`), `HERALD_BRIDGE_MIGRATE=0`, automatic
55
+ updates turned off, or a tunnel for a non-default `HERMES_HOME`.
56
+
57
+ ## How it works
58
+
59
+ The plugin dials OUT from your machine to Herald Cloud. No port forwarding needed.
60
+ Hermes works normally; Herald notifies you on mobile when it needs you or finishes a task.
61
+
62
+ ## Configuration
63
+
64
+ | Key (`herald:` in `~/.hermes/config.yaml`) | Default | Description |
65
+ |-----|---------|-------------|
66
+ | `relay_url` | `https://herald-api.eventhorizonlabs.xyz` | Herald relay this machine dials out to |
67
+ | `device_token` | registered by `setup` | Identifies this machine at the relay |
68
+ | `auto_update` | `true` | `false` pins this version |
69
+
70
+ ## Environment variables
71
+
72
+ - `HERALD_RELAY_URL`, `HERALD_DEVICE_TOKEN` — fallbacks if the `herald:` block is missing
73
+ - `HERALD_LOCAL_HERMES_URL` — override local Hermes URL (default: `http://127.0.0.1:8642`)
74
+ - `HERALD_BRIDGE_AUTO_UPDATE=0` — turn automatic updates off (or `herald.auto_update: false`
75
+ in `~/.hermes/config.yaml`). Also refuses "update now" from the app.
76
+ - `HERALD_BRIDGE_MIGRATE=0` — don't move a bridge installed elsewhere into `~/.herald-relay`.
77
+
78
+ ## Automatic updates (0.8.0+)
79
+
80
+ `herald-tunnel run` keeps Herald Bridge up to date by itself (`herald_relay/bridge_update.py`):
81
+
82
+ 1. On start, every 6 h (± 30 min jitter), when the relay hints a newer release on connect,
83
+ and when the app or an operator asks ("update now"), it fetches
84
+ `GET <relay>/relay/plugin/manifest`: a DSSE envelope signed offline with Ed25519
85
+ (`scripts/release_plugin.py`; the public key is compiled into the plugin). Expired
86
+ manifests and versions not newer than the running one are refused.
87
+ 2. Machines in the release's `rollout_percent` slice (stable per machine) download the wheel
88
+ (size-capped, sha256-checked) and install it into a NEW venv,
89
+ `~/.herald-relay-versions/<version>`, which must pass `herald-tunnel selfcheck`.
90
+ 3. When nothing has been in flight for 20 s (no run, no forwarded request, no approval), the
91
+ stable path `~/.herald-relay` is flipped to the new venv with one `rename(2)` and the
92
+ tunnel re-execs itself. systemd, the keepalive and skills keep using `~/.herald-relay`.
93
+ 4. The new version is on probation until it registers with the relay. If it crash-loops
94
+ (3 starts) or cannot register while the relay is reachable, `~/.herald-relay` is flipped
95
+ back, the version is marked bad and the previous build restarts.
96
+
97
+ Only a venv Herald owns is updated: `~/.herald-relay`, `~/.herald/venv` (Herald Cloud), or
98
+ `HERALD_BRIDGE_ROOT`. A bridge installed anywhere else moves itself into `~/.herald-relay`
99
+ first (see "Installed somewhere else?" above). `herald-tunnel update` asks for an update now;
100
+ `herald-tunnel update --status` shows the last result. Machines on 0.7.x and older have no
101
+ updater: they need one manual `pip install -U` to reach 0.8.0 (0.8.1+ when installed outside
102
+ `~/.herald-relay`, so the move kicks in).
103
+
104
+ Releasing: `python scripts/release_plugin.py --rollout 10` (builds, attaches the wheel to
105
+ GitHub release `plugin-v<version>`, signs with Secret Manager `herald-relay-signing-key`,
106
+ writes `backend/release/plugin-manifest.json`), merge that file, then
107
+ `--resign --rollout 100` when the first slice is healthy. The relay counts machines per
108
+ version at `GET /relay/plugin/versions` (header `X-Herald-Ops-Token`).
109
+
110
+ ## Herald Bridge keeps Hermes updated (0.9.0+)
111
+
112
+ Hermes has no automatic update. `herald-tunnel run` updates it, but only to the Hermes
113
+ release Herald tested, and only where that's safe (`herald_relay/hermes_update.py`):
114
+
115
+ - **Signed pin.** The same signed manifest may carry
116
+ `"hermes": {"version", "tag", "git_sha", "rollout_percent"}`, set with
117
+ `release_plugin.py --resign --hermes-tag vX.Y.Z --hermes-rollout 10`. No block means
118
+ nothing happens. A new tag starts at 0 %.
119
+ - **Safe boxes only.** The box must be an official source checkout run by a `hermes-gateway*`
120
+ systemd user unit, with a clean tree and **no local commits**. Carried patches are skipped and
121
+ reported, never clobbered. Herald Cloud (image-managed), forks and opted-out boxes are skipped.
122
+ - **Never past the tested release, never backwards.** The upstream tag must be the signed commit
123
+ and the box must be strictly behind it. If upstream already shipped a newer stable release,
124
+ wait, because `hermes update` would go there.
125
+ - **Staged, then idle.** The release is compiled in a throwaway git worktree. It is applied only
126
+ after the gateway has reported no active agent, API run or delegation (`/health/detailed`)
127
+ for 2 minutes.
128
+ - **Hermes installs it.** `hermes update --yes --channel stable --no-gateway-restart` handles
129
+ dependencies, config migrations and the downgrade guard. We check it landed on the signed
130
+ commit.
131
+ - **Restart, health, rollback.** The `hermes-gateway*` units are restarted through the user's
132
+ systemd. Checks: local `/health` must report the new version and `/v1/models` must answer with
133
+ the key. Through the relay, `/health`, `/api/soul` and `/v1/skills` must answer. On any failure
134
+ the checkout goes back to the previous commit, the gateway restarts and is re-checked, and the
135
+ version is marked bad on that box. A failed rollback halts updates there (`rollback_failed`)
136
+ until an operator looks.
137
+ - **Opt out:** `HERALD_HERMES_AUTO_UPDATE=0` or `herald.hermes_auto_update: false`.
138
+ - **Fleet view:** every connect reports `hermes_update` (current, target, state, why skipped).
139
+ `GET /relay/plugin/versions` counts Hermes versions and skip reasons.
140
+ `POST /relay/plugin/update-now {"device_token": …, "hermes": true}` checks one box now
141
+ (skips the rollout slice, never the safety checks).
142
+
143
+ ## Architecture
144
+
145
+ ```
146
+ Mobile App ←→ Herald Cloud ←(WebSocket)→ hermes-herald plugin ←→ Local Hermes
147
+ ```
148
+
149
+ 1. Herald Cloud receives voice/text from your mobile app.
150
+ 2. It forwards the HTTP request over the persistent WebSocket tunnel.
151
+ 3. The plugin proxies it to your local Hermes API and streams the response back.
152
+ 4. When Hermes fires an `approval_required` or completes a long task, the plugin
153
+ sends a push trigger so Herald Cloud wakes your phone.
154
+
155
+ ## Agent name and skills on stock Hermes
156
+
157
+ Herald reads the agent's name from `GET /api/soul` and its skills from
158
+ `GET /v1/skills`. Stock Hermes does not serve the first (404), and its
159
+ `/v1/skills` currently fails (500). The tunnel answers both paths itself, for
160
+ the default profile and `/p/<profile>/…`, whenever local Hermes can't: it asks
161
+ Hermes first and passes a working answer through untouched, otherwise it
162
+ checks the caller holds that profile's key and builds the same answer with
163
+ Hermes' own loaders (`agent_info_helper.py`, run with Hermes' interpreter),
164
+ falling back to reading `SOUL.md` and `skills/**/SKILL.md`. Nothing needs to
165
+ be patched into Hermes, so `hermes update` no longer breaks either.
@@ -0,0 +1,149 @@
1
+ # hermes-herald (Herald Bridge)
2
+
3
+ Connect your local Hermes AI agent to Herald — voice-first conversations on mobile.
4
+
5
+ Full guide: <https://heraldbridge.dev/docs/setup>.
6
+
7
+ ## Install (it keeps itself up to date)
8
+
9
+ Install into its own venv at `~/.herald-relay`, the only place Herald Bridge can
10
+ update itself. `hermes-herald` is not published on PyPI; install it from GitHub:
11
+
12
+ ```bash
13
+ python3 -m venv ~/.herald-relay
14
+ ~/.herald-relay/bin/pip install "git+https://github.com/Mohit-Ak/herald-relay#subdirectory=plugin"
15
+ ~/.herald-relay/bin/herald-tunnel setup # registers this machine, installs the service
16
+ ~/.herald-relay/bin/herald-tunnel status # local Hermes → relay → this tunnel, end to end
17
+ ```
18
+
19
+ `setup` writes the `herald:` block of `~/.hermes/config.yaml` for you:
20
+
21
+ ```yaml
22
+ herald:
23
+ relay_url: https://herald-api.eventhorizonlabs.xyz
24
+ device_token: <registered by setup>
25
+ # auto_update: false # pin this version
26
+ ```
27
+
28
+ (Older docs said `plugins.herald-relay` and `wss://relay.herald.app`. Nothing reads
29
+ that key, and that host never existed.)
30
+
31
+ **Installed somewhere else?** A bridge installed with `pip install` into Hermes' own
32
+ venv, with `pip --user`, or into any other venv moves itself into `~/.herald-relay`:
33
+ `herald-tunnel setup` does it before writing anything, and a running tunnel does it
34
+ in the background once nothing is in flight (`herald_relay/migrate.py`). It installs
35
+ the release named by the signed manifest, rewrites only the `ExecStart` line of the
36
+ systemd user unit (and the keepalive script and skills), and re-execs from there. The
37
+ device token and settings live in `~/.hermes/config.yaml`, so pairing is unchanged.
38
+ Not moved: developer checkouts (`pip install -e`), `HERALD_BRIDGE_MIGRATE=0`, automatic
39
+ updates turned off, or a tunnel for a non-default `HERMES_HOME`.
40
+
41
+ ## How it works
42
+
43
+ The plugin dials OUT from your machine to Herald Cloud. No port forwarding needed.
44
+ Hermes works normally; Herald notifies you on mobile when it needs you or finishes a task.
45
+
46
+ ## Configuration
47
+
48
+ | Key (`herald:` in `~/.hermes/config.yaml`) | Default | Description |
49
+ |-----|---------|-------------|
50
+ | `relay_url` | `https://herald-api.eventhorizonlabs.xyz` | Herald relay this machine dials out to |
51
+ | `device_token` | registered by `setup` | Identifies this machine at the relay |
52
+ | `auto_update` | `true` | `false` pins this version |
53
+
54
+ ## Environment variables
55
+
56
+ - `HERALD_RELAY_URL`, `HERALD_DEVICE_TOKEN` — fallbacks if the `herald:` block is missing
57
+ - `HERALD_LOCAL_HERMES_URL` — override local Hermes URL (default: `http://127.0.0.1:8642`)
58
+ - `HERALD_BRIDGE_AUTO_UPDATE=0` — turn automatic updates off (or `herald.auto_update: false`
59
+ in `~/.hermes/config.yaml`). Also refuses "update now" from the app.
60
+ - `HERALD_BRIDGE_MIGRATE=0` — don't move a bridge installed elsewhere into `~/.herald-relay`.
61
+
62
+ ## Automatic updates (0.8.0+)
63
+
64
+ `herald-tunnel run` keeps Herald Bridge up to date by itself (`herald_relay/bridge_update.py`):
65
+
66
+ 1. On start, every 6 h (± 30 min jitter), when the relay hints a newer release on connect,
67
+ and when the app or an operator asks ("update now"), it fetches
68
+ `GET <relay>/relay/plugin/manifest`: a DSSE envelope signed offline with Ed25519
69
+ (`scripts/release_plugin.py`; the public key is compiled into the plugin). Expired
70
+ manifests and versions not newer than the running one are refused.
71
+ 2. Machines in the release's `rollout_percent` slice (stable per machine) download the wheel
72
+ (size-capped, sha256-checked) and install it into a NEW venv,
73
+ `~/.herald-relay-versions/<version>`, which must pass `herald-tunnel selfcheck`.
74
+ 3. When nothing has been in flight for 20 s (no run, no forwarded request, no approval), the
75
+ stable path `~/.herald-relay` is flipped to the new venv with one `rename(2)` and the
76
+ tunnel re-execs itself. systemd, the keepalive and skills keep using `~/.herald-relay`.
77
+ 4. The new version is on probation until it registers with the relay. If it crash-loops
78
+ (3 starts) or cannot register while the relay is reachable, `~/.herald-relay` is flipped
79
+ back, the version is marked bad and the previous build restarts.
80
+
81
+ Only a venv Herald owns is updated: `~/.herald-relay`, `~/.herald/venv` (Herald Cloud), or
82
+ `HERALD_BRIDGE_ROOT`. A bridge installed anywhere else moves itself into `~/.herald-relay`
83
+ first (see "Installed somewhere else?" above). `herald-tunnel update` asks for an update now;
84
+ `herald-tunnel update --status` shows the last result. Machines on 0.7.x and older have no
85
+ updater: they need one manual `pip install -U` to reach 0.8.0 (0.8.1+ when installed outside
86
+ `~/.herald-relay`, so the move kicks in).
87
+
88
+ Releasing: `python scripts/release_plugin.py --rollout 10` (builds, attaches the wheel to
89
+ GitHub release `plugin-v<version>`, signs with Secret Manager `herald-relay-signing-key`,
90
+ writes `backend/release/plugin-manifest.json`), merge that file, then
91
+ `--resign --rollout 100` when the first slice is healthy. The relay counts machines per
92
+ version at `GET /relay/plugin/versions` (header `X-Herald-Ops-Token`).
93
+
94
+ ## Herald Bridge keeps Hermes updated (0.9.0+)
95
+
96
+ Hermes has no automatic update. `herald-tunnel run` updates it, but only to the Hermes
97
+ release Herald tested, and only where that's safe (`herald_relay/hermes_update.py`):
98
+
99
+ - **Signed pin.** The same signed manifest may carry
100
+ `"hermes": {"version", "tag", "git_sha", "rollout_percent"}`, set with
101
+ `release_plugin.py --resign --hermes-tag vX.Y.Z --hermes-rollout 10`. No block means
102
+ nothing happens. A new tag starts at 0 %.
103
+ - **Safe boxes only.** The box must be an official source checkout run by a `hermes-gateway*`
104
+ systemd user unit, with a clean tree and **no local commits**. Carried patches are skipped and
105
+ reported, never clobbered. Herald Cloud (image-managed), forks and opted-out boxes are skipped.
106
+ - **Never past the tested release, never backwards.** The upstream tag must be the signed commit
107
+ and the box must be strictly behind it. If upstream already shipped a newer stable release,
108
+ wait, because `hermes update` would go there.
109
+ - **Staged, then idle.** The release is compiled in a throwaway git worktree. It is applied only
110
+ after the gateway has reported no active agent, API run or delegation (`/health/detailed`)
111
+ for 2 minutes.
112
+ - **Hermes installs it.** `hermes update --yes --channel stable --no-gateway-restart` handles
113
+ dependencies, config migrations and the downgrade guard. We check it landed on the signed
114
+ commit.
115
+ - **Restart, health, rollback.** The `hermes-gateway*` units are restarted through the user's
116
+ systemd. Checks: local `/health` must report the new version and `/v1/models` must answer with
117
+ the key. Through the relay, `/health`, `/api/soul` and `/v1/skills` must answer. On any failure
118
+ the checkout goes back to the previous commit, the gateway restarts and is re-checked, and the
119
+ version is marked bad on that box. A failed rollback halts updates there (`rollback_failed`)
120
+ until an operator looks.
121
+ - **Opt out:** `HERALD_HERMES_AUTO_UPDATE=0` or `herald.hermes_auto_update: false`.
122
+ - **Fleet view:** every connect reports `hermes_update` (current, target, state, why skipped).
123
+ `GET /relay/plugin/versions` counts Hermes versions and skip reasons.
124
+ `POST /relay/plugin/update-now {"device_token": …, "hermes": true}` checks one box now
125
+ (skips the rollout slice, never the safety checks).
126
+
127
+ ## Architecture
128
+
129
+ ```
130
+ Mobile App ←→ Herald Cloud ←(WebSocket)→ hermes-herald plugin ←→ Local Hermes
131
+ ```
132
+
133
+ 1. Herald Cloud receives voice/text from your mobile app.
134
+ 2. It forwards the HTTP request over the persistent WebSocket tunnel.
135
+ 3. The plugin proxies it to your local Hermes API and streams the response back.
136
+ 4. When Hermes fires an `approval_required` or completes a long task, the plugin
137
+ sends a push trigger so Herald Cloud wakes your phone.
138
+
139
+ ## Agent name and skills on stock Hermes
140
+
141
+ Herald reads the agent's name from `GET /api/soul` and its skills from
142
+ `GET /v1/skills`. Stock Hermes does not serve the first (404), and its
143
+ `/v1/skills` currently fails (500). The tunnel answers both paths itself, for
144
+ the default profile and `/p/<profile>/…`, whenever local Hermes can't: it asks
145
+ Hermes first and passes a working answer through untouched, otherwise it
146
+ checks the caller holds that profile's key and builds the same answer with
147
+ Hermes' own loaders (`agent_info_helper.py`, run with Hermes' interpreter),
148
+ falling back to reading `SOUL.md` and `skills/**/SKILL.md`. Nothing needs to
149
+ be patched into Hermes, so `hermes update` no longer breaks either.
@@ -0,0 +1,13 @@
1
+ """Herald Relay plugin for Hermes — connects your local Hermes to Herald Cloud."""
2
+ __version__ = "0.9.0"
3
+
4
+
5
+ def is_local_door(path: str) -> bool:
6
+ """A path the tunnel answers itself (``/_herald/...``), never Hermes.
7
+
8
+ One list for both transports (SSE forward and the edge socket), so a new
9
+ door can't be wired into one and silently missed in the other.
10
+ """
11
+ from herald_relay import agent_info, local_bridge, local_passwords, local_screen # noqa: PLC0415
12
+ return bool(local_screen.matches(path) or local_passwords.matches(path)
13
+ or agent_info.matches(path) or local_bridge.matches(path))
@@ -0,0 +1,248 @@
1
+ """The agent's name (SOUL.md) and skills list, served even when Hermes can't.
2
+
3
+ Herald reads two things from every agent:
4
+
5
+ GET [/p/<profile>]/api/soul {"soul": "...", ...} -> the agent's name
6
+ GET [/p/<profile>]/v1/skills {"object": "list", "data": [...]}
7
+
8
+ Stock Hermes does not serve the first at all (404), and its /v1/skills 500s
9
+ on current releases (it still passes ``include_editorial`` to
10
+ ``find_all_skills()``, which no longer takes it). Customers used to carry both
11
+ fixes as hand-applied patches to ~/.hermes/hermes-agent, and ``hermes update``
12
+ stashes local changes, so after every update the app showed "default" instead
13
+ of the agent's name and the skills drawer failed (herald#490).
14
+
15
+ So the tunnel answers these two paths itself when Hermes can't:
16
+
17
+ 1. Ask local Hermes first, with the caller's own key. A 200 is passed through
18
+ untouched: when Hermes serves them (patched, or a future release that fixes
19
+ them), Hermes is the authority. A 401/403 is passed through too.
20
+ 2. Otherwise (404, 405, 5xx, a body that isn't JSON), check that the caller
21
+ holds THAT profile's key (the same check as the screen routes: present it
22
+ to that profile's ``/v1/models``), then build the answer with Hermes' OWN
23
+ code, run with Hermes' interpreter and that profile's HERMES_HOME
24
+ (``agent_info_helper.py``: ``load_soul_md`` / ``find_all_skills``), so the
25
+ result is what the agent itself sees.
26
+ 3. If even that fails (a Hermes whose internals moved), read the files
27
+ directly: ``SOUL.md`` and each ``skills/**/SKILL.md`` front matter.
28
+
29
+ Nothing here writes anything, and the machine's own key is never substituted
30
+ for the caller's.
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import asyncio
35
+ import json
36
+ import logging
37
+ import os
38
+ import re
39
+ from pathlib import Path
40
+
41
+ import aiohttp
42
+
43
+ logger = logging.getLogger("herald.agent_info")
44
+
45
+ _ROUTE = re.compile(
46
+ r"^(?:/p/(?P<profile>[A-Za-z0-9][A-Za-z0-9_.-]{0,63}))?/(?P<what>api/soul|v1/skills)/?$")
47
+ _HELPER = Path(__file__).with_name("agent_info_helper.py")
48
+
49
+
50
+ def _argv_of(py) -> list[str]:
51
+ """A path (Hermes in a venv) or an argv prefix (tunnel_cli._hermes_command)."""
52
+ if not py:
53
+ return []
54
+ return [py] if isinstance(py, str) else [str(x) for x in py]
55
+ HELPER_TIMEOUT_S = 30.0
56
+ UPSTREAM_TIMEOUT_S = 30.0
57
+ # Same caps Hermes' own loaders use in spirit: one persona file, a sane skill tree.
58
+ MAX_SOUL_BYTES = 64 * 1024
59
+ MAX_SKILLS = 2000
60
+ MAX_DESCRIPTION = 1024
61
+ # Marks an answer this tunnel built, so a support check can tell the two apart.
62
+ SOURCE = "herald-relay"
63
+
64
+
65
+ def matches(path: str) -> bool:
66
+ return _ROUTE.match((path or "").split("?", 1)[0]) is not None
67
+
68
+
69
+ def _auth(headers: dict) -> str:
70
+ return next((v for k, v in (headers or {}).items()
71
+ if k.lower() == "authorization" and v), "")
72
+
73
+
74
+ async def _upstream(hermes_url: str, path: str, auth: str):
75
+ """(status, parsed JSON or None); raises on transport failure."""
76
+ hdrs = {"Accept": "application/json"}
77
+ if auth:
78
+ hdrs["Authorization"] = auth
79
+ async with aiohttp.ClientSession() as http:
80
+ async with http.get(f"{hermes_url}{path}", headers=hdrs,
81
+ timeout=aiohttp.ClientTimeout(total=UPSTREAM_TIMEOUT_S)) as r:
82
+ text = await r.text()
83
+ try:
84
+ return r.status, json.loads(text)
85
+ except ValueError:
86
+ return r.status, None
87
+
88
+
89
+ async def _from_hermes(py, home: Path, op: str) -> dict | None:
90
+ """Run agent_info_helper.py with Hermes' interpreter; its JSON, or None."""
91
+ if not py:
92
+ return None
93
+ env = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"}
94
+ env["HERMES_HOME"] = str(home)
95
+ try:
96
+ proc = await asyncio.create_subprocess_exec(
97
+ *_argv_of(py), str(_HELPER), stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
98
+ stderr=asyncio.subprocess.DEVNULL, env=env, start_new_session=True)
99
+ except OSError:
100
+ return None
101
+ try:
102
+ out, _ = await asyncio.wait_for(proc.communicate(json.dumps({"op": op}).encode()),
103
+ HELPER_TIMEOUT_S)
104
+ except asyncio.TimeoutError:
105
+ proc.kill()
106
+ await proc.wait()
107
+ logger.warning("agent info helper timed out (%s)", op)
108
+ return None
109
+ for line in reversed(out.decode("utf-8", "replace").splitlines()):
110
+ line = line.strip()
111
+ if line.startswith("{"):
112
+ try:
113
+ ans = json.loads(line)
114
+ except ValueError:
115
+ continue
116
+ return ans if isinstance(ans, dict) and "error" not in ans else None
117
+ return None
118
+
119
+
120
+ # ── last resort: the files themselves ───────────────────────────────────────
121
+
122
+ def soul_from_disk(home: Path) -> str | None:
123
+ p = home / "SOUL.md"
124
+ try:
125
+ with open(p, "rb") as f:
126
+ text = f.read(MAX_SOUL_BYTES).decode("utf-8", "replace").strip()
127
+ except OSError:
128
+ return None
129
+ return text or None
130
+
131
+
132
+ _FM = re.compile(r"\A---\s*\n(.*?)\n---\s*(?:\n|\Z)", re.S)
133
+
134
+
135
+ def _front_matter(text: str) -> dict:
136
+ m = _FM.match(text)
137
+ if not m:
138
+ return {}
139
+ try:
140
+ import yaml # noqa: PLC0415 (a dependency of this package)
141
+ data = yaml.safe_load(m.group(1))
142
+ return data if isinstance(data, dict) else {}
143
+ except Exception: # noqa: BLE001 a broken header must not drop the whole list
144
+ out = {}
145
+ for line in m.group(1).splitlines():
146
+ k, sep, v = line.partition(":")
147
+ if sep and k.strip() in ("name", "description"):
148
+ out[k.strip()] = v.strip().strip("'\"")
149
+ return out
150
+
151
+
152
+ def skills_from_disk(home: Path) -> list[dict]:
153
+ """``{name, description, category}`` for every SKILL.md under <home>/skills."""
154
+ root = home / "skills"
155
+ if not root.is_dir():
156
+ return []
157
+ seen: dict[str, dict] = {}
158
+ for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
159
+ # Hidden dirs hold Hermes' own bookkeeping (.hub, .archive, ...).
160
+ dirnames[:] = sorted(d for d in dirnames if not d.startswith((".", "_")))
161
+ if "SKILL.md" not in filenames:
162
+ continue
163
+ rel = Path(dirpath).relative_to(root)
164
+ try:
165
+ with open(Path(dirpath) / "SKILL.md", "rb") as f:
166
+ text = f.read(32 * 1024).decode("utf-8", "replace")
167
+ except OSError:
168
+ continue
169
+ fm = _front_matter(text)
170
+ name = str(fm.get("name") or rel.name).strip()
171
+ if not name or name in seen:
172
+ continue
173
+ desc = fm.get("description")
174
+ desc = " ".join(str(desc).split())[:MAX_DESCRIPTION] if desc else ""
175
+ category = rel.parts[0] if len(rel.parts) > 1 else None
176
+ seen[name] = {"name": name, "description": desc, "category": category}
177
+ if len(seen) >= MAX_SKILLS:
178
+ break
179
+ return sorted(seen.values(), key=lambda s: (s.get("category") or "", s["name"]))
180
+
181
+
182
+ # ── the handler ─────────────────────────────────────────────────────────────
183
+
184
+ def _home(root: Path, profile: str | None) -> Path | None:
185
+ if not profile:
186
+ return root
187
+ home = root / "profiles" / profile
188
+ return home if home.is_dir() else None
189
+
190
+
191
+ async def _caller_owns(hermes_url: str, prefix: str, auth: str) -> bool:
192
+ if not auth.strip() or auth.strip().lower() == "bearer":
193
+ return False
194
+ try:
195
+ async with aiohttp.ClientSession() as http:
196
+ async with http.get(f"{hermes_url}{prefix}/v1/models", headers={"Authorization": auth},
197
+ timeout=aiohttp.ClientTimeout(total=10)) as r:
198
+ return r.status == 200
199
+ except Exception: # noqa: BLE001
200
+ return False
201
+
202
+
203
+ async def handle(method: str, path: str, headers: dict, body, *, hermes_url: str,
204
+ hermes_home: Path, hermes_python) -> tuple[int, dict | list]:
205
+ m = _ROUTE.match((path or "").split("?", 1)[0])
206
+ if m is None:
207
+ return 404, {"error": "not_found", "message": "Not found."}
208
+ if (method or "GET").upper() != "GET":
209
+ return 405, {"error": "method_not_allowed", "message": "Method not allowed."}
210
+ hermes_url = hermes_url.rstrip("/")
211
+ profile, what = m.group("profile"), m.group("what")
212
+ prefix = f"/p/{profile}" if profile else ""
213
+ auth = _auth(headers)
214
+
215
+ try:
216
+ status, parsed = await _upstream(hermes_url, path, auth)
217
+ except Exception as exc: # noqa: BLE001
218
+ logger.warning("agent info: local Hermes unreachable: %s", type(exc).__name__)
219
+ return 502, {"error": "hermes_unreachable", "message": "This computer's agent isn't answering."}
220
+ if status == 200 and isinstance(parsed, (dict, list)):
221
+ return 200, parsed
222
+ if status in (401, 403):
223
+ return status, parsed if isinstance(parsed, dict) else {"error": "unauthorized"}
224
+
225
+ # Hermes can't answer this one (stock Hermes: 404 soul, 500 skills).
226
+ if not await _caller_owns(hermes_url, prefix, auth):
227
+ return 401, {"error": "agent_key_required", "message": "Send this agent's API key with the request."}
228
+ home = _home(Path(hermes_home), profile)
229
+ if home is None:
230
+ return 404, {"error": "not_found", "message": "We couldn't find that agent."}
231
+
232
+ op = "soul" if what == "api/soul" else "skills"
233
+ ans = await _from_hermes(hermes_python, home, op)
234
+ via = "hermes"
235
+ if op == "soul":
236
+ if ans is None or not (ans.get("soul") is None or isinstance(ans.get("soul"), str)):
237
+ soul, via = soul_from_disk(home), "disk"
238
+ else:
239
+ soul = ans.get("soul")
240
+ logger.info("served /api/soul for %s (upstream %s, via %s)", profile or "default", status, via)
241
+ return 200, {"object": "hermes.soul", "profile": profile or "default", "soul": soul,
242
+ "chars": len(soul) if soul else 0, "source": SOURCE}
243
+ data = ans.get("data") if isinstance(ans, dict) else None
244
+ if not isinstance(data, list):
245
+ data, via = skills_from_disk(home), "disk"
246
+ logger.info("served /v1/skills for %s: %d (upstream %s, via %s)",
247
+ profile or "default", len(data), status, via)
248
+ return 200, {"object": "list", "data": data, "source": SOURCE}