Compare commits

..
Author SHA1 Message Date
Bailey Dixon 7440ef2948 Merge pull request #343 from Codename-11/dev
release: server 1.7.0 and desktop 0.4.0-alpha.8
2026-08-13 17:14:58 -04:00
Bailey Dixon a88539bc59 fix(android): dequeue reach frames compatibly 2026-08-13 16:56:54 -04:00
Bailey Dixon b2ccfdc500 fix(security): carry secure link trust anchor 2026-08-13 16:49:44 -04:00
Bailey Dixon 481c62ac59 fix(desktop): bind pinned secure link probes 2026-08-13 16:42:37 -04:00
Bailey Dixon 5d415fbaf0 fix(android): use compatible reach buffer removal 2026-08-13 16:39:26 -04:00
Bailey Dixon 074b715055 fix(android): complete secure route translations 2026-08-13 16:37:32 -04:00
Bailey Dixon f63ee8721e release(desktop): desktop-v0.4.0-alpha.8 2026-08-13 16:21:51 -04:00
Bailey Dixon 777bc80bcc release(server): server-v1.7.0 2026-08-13 16:21:50 -04:00
Bailey Dixon 9539975bb5 merge: integrate native secure routes 2026-08-13 15:41:46 -04:00
Bailey Dixon 2863a1bc8f merge: reconcile native secure routes with dev 2026-08-13 15:31:53 -04:00
Bailey Dixon b0a7cf0494 feat: add self-hosted secure connection routes 2026-08-13 15:31:46 -04:00
Bailey Dixon 76b4084310 merge: integrate Android and Relay upstream work 2026-08-13 13:24:32 -04:00
Bailey Dixon 2ace70c4fc test: close integration verification gaps 2026-08-13 13:24:02 -04:00
Bailey Dixon 4f52f371ba fix(ops): fail closed on unsafe certification state 2026-08-13 11:16:27 -04:00
Bailey Dixon 064c89bda4 docs: record Android and Relay integration 2026-08-13 11:08:27 -04:00
Bailey Dixon 0cb1e3642f feat(android): add gateway-native profile editor 2026-08-13 11:03:10 -04:00
Bailey Dixon cf4bf87242 fix(android): honor upstream routing contracts 2026-08-13 11:00:39 -04:00
Bailey Dixon 9cbed21014 fix(android): preserve durable gateway rewinds 2026-08-13 10:58:55 -04:00
Bailey Dixon ce75c0fa01 docs: add controlled runtime safety preflight 2026-08-13 10:50:52 -04:00
Bailey Dixon bf2aece6e6 docs: reconcile upstream architecture evaluations 2026-08-13 10:50:14 -04:00
Bailey Dixon 198da78fc8 fix(android): honor upstream approval and compression outcomes 2026-08-13 10:50:14 -04:00
Bailey Dixon 986ce3b12b fix(plugin): isolate profile-owned registrations 2026-08-13 10:50:14 -04:00
Bailey Dixon b53f757830 fix(plugin): support strict phone targets 2026-08-13 10:50:14 -04:00
Bailey Dixon cdeccd69e4 feat: add secure relay route selection 2026-08-12 20:10:41 -04:00
Bailey Dixon bb72516bb5 Merge pull request #340 from Codename-11/chore/backmerge-server-1.6.4
chore: back-merge server-v1.6.4 hotfix
2026-08-12 18:43:50 -04:00
Bailey Dixon 3a51644342 chore: merge server-v1.6.4 release history into dev
# Conflicts:
#	docs/decisions.md
#	user-docs/desktop/tools.md
2026-08-12 18:43:39 -04:00
Bailey Dixon 51c0c7dee9 Merge pull request #338 from Codename-11/fix/server-multidevice-hotfix
fix(server): release targeted multi-desktop routing
2026-08-12 18:39:31 -04:00
Bailey Dixon 7ef2420c85 release(server): server-v1.6.4 2026-08-12 18:38:32 -04:00
Bailey Dixon 6a810c850b fix(server): route concurrent desktop clients explicitly 2026-08-12 18:38:02 -04:00
Bailey Dixon d383002583 Merge pull request #336 from Codename-11/release/server-1.6.4
release(server): server-v1.6.4
2026-08-12 18:35:31 -04:00
Bailey Dixon e3aae829e1 release(server): server-v1.6.4 2026-08-12 18:35:16 -04:00
Bailey Dixon 5207ed4193 Merge pull request #335 from Codename-11/fix/desktop-placement-device-identity
feat(desktop): support targeted multi-device control
2026-08-12 18:32:06 -04:00
Bailey Dixon b46bb00ea8 test(desktop): serialize cross-platform suite 2026-08-12 18:31:50 -04:00
Bailey Dixon b8dde409c5 merge: synchronize desktop management with dev
# Conflicts:
#	CHANGELOG.md
#	docs/decisions.md
2026-08-12 18:26:20 -04:00
Bailey Dixon ca7ded3939 test(server): prove concurrent desktop routing 2026-08-12 18:24:44 -04:00
Bailey Dixon db85a26c68 feat(desktop): add contextual approvals and UI pairing 2026-08-12 18:24:43 -04:00
Bailey Dixon aa2595629d feat(desktop): expand tray management controls 2026-08-12 17:55:56 -04:00
Bailey Dixon d79146dc90 feat(desktop): add ask every time access preset 2026-08-12 17:13:51 -04:00
Bailey Dixon eabc4dd328 refactor(desktop): clarify access navigation 2026-08-12 16:57:50 -04:00
Bailey Dixon e165bfeff3 feat(desktop): animate bidirectional relay traffic 2026-08-12 15:42:43 -04:00
Bailey Dixon 40bcd796d1 refactor(desktop): simplify host access presets 2026-08-12 13:29:29 -04:00
Bailey Dixon 57ae0c9456 feat(desktop): unify capabilities and activity drilldown 2026-08-12 13:06:34 -04:00
Bailey Dixon 9b31a16c89 fix(desktop): preserve Hermes shortcut icons 2026-08-12 11:44:17 -04:00
Bailey Dixon f97bbdd395 feat(desktop): add host-wide raw USB control 2026-08-12 11:38:09 -04:00
Bailey Dixon 722a294947 feat(desktop): adopt compact capability ledger 2026-08-12 11:13:50 -04:00
Bailey Dixon bbfb57b462 feat(desktop): harden targeted remote management 2026-08-12 10:37:12 -04:00
Bailey Dixon 6db12a0bec merge: complete upstream app and Relay workflows 2026-08-12 09:24:24 -04:00
Bailey Dixon f1de957848 fix(android): translate Manage workflows 2026-08-12 09:08:31 -04:00
Bailey Dixon cc01d9c8ad test(android): compile upstream workflow fixtures 2026-08-12 09:00:04 -04:00
Bailey Dixon d574182d84 fix(android): wire Manage workflow dialogs 2026-08-12 08:46:10 -04:00
Bailey Dixon a328763da3 fix(android): localize backup completion 2026-08-12 08:46:05 -04:00
Bailey Dixon f53db68e7d feat(android): complete upstream Manage workflows 2026-08-12 07:45:55 -04:00
Bailey Dixon eb9e570fc0 feat(android): show session repository and PR state 2026-08-12 07:41:35 -04:00
Bailey Dixon 260f119637 fix(voice): align upstream auth and transport 2026-08-12 07:39:42 -04:00
Bailey Dixon d0fa2ea39d fix(android): preserve clarify selection semantics 2026-08-12 07:37:28 -04:00
Bailey Dixon a1c74b1567 fix(plugin): enumerate phone home target 2026-08-12 07:34:19 -04:00
Bailey Dixon 7c45acd38d chore: merge server-v1.6.3 release history into dev 2026-08-11 22:03:36 -04:00
209 changed files with 17688 additions and 1516 deletions
+64 -1
View File
@@ -6,11 +6,74 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
## [Unreleased]
### Added
- **Android can edit current Hermes profiles through the standard Gateway.** The Profile Inspector capability-gates `profiles.describe` and `profiles.configure`, keeps Relay-only memory editing and older-Hermes fallback intact, and reports partial section saves without discarding failed drafts.
- **Android sessions show their coding context when Hermes supplies it.** Session rows can display repository, Git branch, and the current state of the pull request created by that session while older hosts remain unchanged.
- Android Manage can now finish host-owned backup workflows, edit or remove learning nodes with explicit recovery guidance, configure and activate memory providers, and complete profile-scoped WhatsApp QR onboarding through the authenticated upstream Dashboard contracts.
### Fixed
- **Android preserves authoritative Gateway outcomes.** Protected-file cards cannot offer forbidden persistent scopes, compression no-ops show the server result, bounded resume failures do not create context-free replacement sessions, and edit/regenerate retains durable row identities across consecutive rewinds.
- **Android routes and uploads against live upstream truth.** Multiplex API fallback trusts `served_profiles` instead of installed profiles, and generic documents carry the Gateway-issued `@file:` reference into ordinary and queued prompts.
- **Android clarify cards preserve upstream decision semantics.** Multi-select prompts keep independent selections and submit one exact list, while server expiry events—not an invented local deadline—retire unanswered cards.
- **Android keeps profile management and retained automation truthful.** Custom Endpoint list and mutation routes now follow the selected Hermes profile, while completed one-shot cron jobs show their retained outcome and expose only valid Runs/Delete actions.
- **Android and Relay recover more generated media reliably.** Android accepts upstream-valid wrapped, punctuated, adjacent, spaced, and Windows `MEDIA:` markers without consuming fenced examples, and Relay translates Docker-visible workspace, home, cache, and configured-mount paths before applying its existing credential, sandbox, and size checks.
## [1.7.0] - 2026-08-13
### Added
- **Hermes Secure Link provides self-hosted pinned TLS ingress.** Relay, API, and Dashboard namespaces share one operator-owned TLS endpoint while retaining their native authentication boundaries, QR-carried certificate continuity, explicit rotation, and fail-closed route validation.
- **Hermes Reach is available for explicit experimentation.** The optional self-hosted rendezvous broker carries opaque Secure Link TLS records over outbound-only connections with bounded multiplexing, hashed credentials, replay protection, persistence, revocation, and no access to Hermes payloads.
- **Remote-access management exposes supported reachability clearly.** Dashboard status and pairing metadata distinguish Tailscale reachability, Secure Link transport protection, direct routes, and experimental Reach without presenting the broker as a replacement for authentication.
### Changed
- **Tailscale is the recommended remote route.** Pairing, Dashboard, documentation, and public site guidance present Tailscale as the easiest supported remote-access path; Reach remains disabled by default, advanced, and lower priority than supported routes.
- **Relay voice custom transports follow upstream provider security options.** Relay-owned OpenAI/xAI realtime and TTS clients honor custom headers, custom CA bundles, standard CA environment precedence, and an explicitly warned development-only verification override.
- **Voice Lab xAI sign-in uses device authorization.** The standalone login shows a verification URL and user code and polls for approval without requiring a loopback callback.
### Fixed
- **Phone delivery remains compatible with strict Hermes targets.** Version-tolerant parser and validator hooks retain older-host registration and exactly-once standalone delivery.
- **Profile-owned Relay registrations stay isolated.** Current Hermes uses profile-scoped ownership and context-local profile homes while legacy hosts retain a guarded compatibility path.
- **Phone is discoverable before its first historical session.** The Relay phone adapter publishes its configured home destination through Hermes' standard channel directory.
## [0.4.0-alpha.8] - 2026-08-13
### Added
- **Windows management separates each Relay host from this PC.** Host detail owns identity, pairing, access, capabilities, authorized clients, re-pairing, and guarded removal; Settings owns local daemon lifecycle, startup, privilege, terminal, logs, diagnostics, updates, and Help & About.
- **Desktop access uses clear host-scoped presets and capabilities.** Restricted, Ask Every Time, Standard, Full Access, and Custom remain explicit across commands, files, screen/input, USB, microphone, and camera controls.
- **Activity drilldown preserves bounded execution evidence.** Overview shows the latest three events and detail views expose request, output, result, exit, duration, and truncation metadata without copying sensitive inputs.
- **Connection presentation shows the live Agent-to-PC path.** Host selection, bidirectional packet motion, transition feedback, route details, and connection testing stay compact, responsive, and reduced-motion aware.
### Changed
- **Connect and disconnect remain responsive during daemon work.** Lifecycle calls and snapshot collection run outside the UI thread, transition status polls quickly without overlapping probes, and progress remains visible until authoritative daemon state arrives.
- **Tailscale is recommended for remote access.** Secure Link and direct TLS routes remain supported, while Hermes Reach is visibly experimental and lower priority.
### Fixed
- **Connection tests classify legacy private routes correctly.** A saved generic role is inferred from its actual endpoint, so LAN and Tailscale routes no longer appear as Custom VPN; results include reachability, latency, security, endpoint, and route count.
- **Ask-mode approval cards show the requested action.** A bounded preview appears in the compact card with full context and an Open in UI action.
- **Mixed capability policies are labeled Custom.** Overview no longer claims a preset when individual capability controls differ.
- **Tray placement follows the notification-area monitor and DPI.** Responsive popup geometry stays anchored above the tray icon across compact and high-DPI desktops.
- **PowerShell success output is complete and self-describing.** Scalar, pipeline, JSON, native stdout/stderr, exit status, and truncation metadata survive the desktop RPC response.
## [1.6.4] - 2026-08-12
### Added
- **Desktop tools support explicit host targeting.** Every client-routed desktop tool accepts a stable device ID or unambiguous computer name, and `/desktop/health` enumerates connected targets and their advertised tools.
- **USB operations retain both routing scopes.** Raw USB and ADB tools use `device` to select the desktop PC, while ADB operations continue to use `serial` to select hardware attached to that PC.
### Fixed
- **Multiple desktop clients remain connected simultaneously.** The Relay no longer replaces the previous desktop when another heartbeat arrives; concurrent requests are bound to their selected WebSockets, responses from another PC are ignored, and an untargeted call fails closed when several desktops are online.
- **Pairing another desktop preserves existing credentials.** Legacy placeholder device identifiers are treated as absent instead of shared ownership, preventing an unrelated PC from revoking the first desktop's session.
## [1.6.3] - 2026-08-11
### Fixed
@@ -581,7 +644,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
- **Spoken-turn badges (chat).** Voice-mode replies now carry a "Voice" chip and realtime replies a "Realtime Agent" chip — both with a speaker glyph — so spoken turns are distinguishable from typed ones in the scrollback.
- **App themes.** A new theme picker in Settings → Appearance ships eight looks: the signature Hermes Relay brand (with full light/dark) plus ports of the Nous Hermes baselines — Hermes Teal, Nous Blue (light), Midnight, Ember, Mono, Cyberpunk, and Rosé. The whole app — brand chrome, accents, and chat background — follows the chosen theme. Light/Dark/Auto applies to themes that ship both modes; fixed-mode themes show their own complete look.
- **Hot-swappable agent sphere.** The orb is now a pluggable "skin": an Adaptive skin that recolors to match your theme, built-in Classic / Aurora / Solar / Mono looks, and support for **user-authored skins** loaded from a small JSON spec. Each skin declares which live signals it reacts to (voice, tool bursts, activity), shown as capability badges in the picker. See `docs/sphere-spec.md`.
- **Connections separate features from routes (Android).** Connection settings now distinguish what a connection can *do* (a **Features** section) from how this phone *reaches* Hermes (a **Route** section), so you can enable Relay features over whichever transport you prefer. A plugin-provided **Secure proxy** route is surfaced alongside LAN, Tailscale, public, and custom routes. The standard direct-to-upstream path is unchanged and still needs no plugin. See `docs/plans/2026-06-18-native-secure-routes.md`.
- **Connections separate features from routes (Android).** Connection settings now distinguish what a connection can *do* (a **Features** section) from how this phone *reaches* Hermes (a **Route** section), so you can enable Relay features over whichever transport you prefer. The optional plugin-provided **Hermes Secure Link** route is surfaced alongside LAN, Tailscale, public, and custom routes. The standard direct-to-upstream path is unchanged and still needs no plugin. See `docs/plans/2026-06-18-native-secure-routes.md`.
- **Enhanced voice control (Gemini & xAI).** When the relay uses a Gemini or xAI voice provider, Voice Settings can now steer it: pick a Gemini voice and model and turn on expressive tone tags (with optional natural-language voice direction), or set an xAI voice with expressive speech tags. Expressive tags also apply to xAI on the streaming voice-output renderer. Standard (no-plugin) voice stays configured server-side.
- **Voice render-path visibility.** Voice Settings shows which path is rendering speech (streaming vs. basic), and Diagnostics records it each session, making voice issues easier to troubleshoot.
- **Agent pets — a living, swappable avatar.** The orb can be replaced with an animated "pet" that reacts to what the agent is doing: idle / thinking / writing / speaking / listening states, a distinct **working** pose during tool calls, one-shot **greet** / **celebrate** reactions, and a loop that quickens as output streams. Add or remove pets right in Settings → Appearance (no `adb` needed), with a live state preview, a playback-speed slider, and optional frame auto-stabilization; capability badges (Voice · Tools · Activity) show honestly what each pet actually reacts to. Pets are pure data — an AI authoring kit and a JSON schema let you generate one from sprite art. See `docs/pet-spec.md` and the custom-avatars guide.
+11 -15
View File
@@ -1,8 +1,8 @@
# Hermes-Relay CLI v__VERSION__
**Release Date:** 2026-08-11
**Release Date:** 2026-08-13
This alpha replaces the right-click-only Windows tray with the compact **Hermes-Relay CLI UI** popup while keeping Hermes-Relay's desktop boundary narrow. Chat, the remote TUI, plugins, voice, and agent sessions remain CLI or upstream desktop concerns.
This alpha makes the compact **Hermes-Relay CLI UI** responsive during connection changes, expands host and capability management, and presents live route security and diagnostics without turning the tray into a full desktop client.
**Experimental phase.** Assets remain unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64, and macOS x64/arm64; the management tray is Windows-only.
@@ -10,25 +10,21 @@ This alpha replaces the right-click-only Windows tray with the compact **Hermes-
### Added
- **Compact Windows management tray.** The popup provides connection status, host selection, per-host access, pending approval dialogs, recent activity, daemon controls, startup settings, and authorized-client revocation.
- **Host-aware desktop access.** `hermes-relay hosts` lists and selects paired Hermes instances and stores independent Ask, Trusted, or Full Access policy for each canonical relay URL.
- **In-window grant decisions.** New computer-use requests bring the tray forward and show the requesting host, scope, reason, and duration with explicit Approve and Reject actions.
- **Supported UI lifecycle from the CLI.** `hermes-relay ui install|open|status` lets a CLI-only Windows installation add, reveal, or inspect the optional management UI without rerunning setup by hand.
- **Host management hub.** Each paired Hermes host has local identity, pairing facts, access and capability controls, authorized-client revocation, re-pairing, and guarded removal.
- **Evidence-first activity.** Overview shows the latest three events and detailed views retain bounded command, output, exit, duration, and truncation evidence.
- **Live route details.** The Agent-to-PC path shows route type, encryption state, endpoint, packet motion, and a connection test with reachability and latency.
### Changed
- **Daemon startup is connectivity-first.** Ask mode can keep an authenticated daemon connected with zero desktop tools attached, so starting the daemon does not itself grant authority.
- **Full Access is explicit and host-scoped.** Trusted hosts may use command and file tools while screen/input remains task-granted. Full Access also removes task prompts for screen, input, and file patches for that host, while authentication, audit, revocation, emergency stop, and UAC boundaries remain enforced.
- **Host changes apply immediately.** Selecting a different host or changing its access mode restarts an already-running daemon and the UI verifies that the daemon URL matches the selected host before showing it as connected.
- **PowerShell remains first-class.** Agents should prefer the dedicated `desktop_powershell` RPC for native Windows work; `desktop_terminal` remains cmd-compatible for existing callers.
- **CLI and UI updates share one verified installer.** Bundle updates coordinate shutdown and restart, allow same-version UI repair, and refuse accidental downgrade unless explicitly forced.
- **Connection lifecycle stays responsive.** Connect, disconnect, and snapshot work run outside the UI thread with immediate transition feedback and single-flight live polling.
- **Access presets are explicit.** Restricted, Ask Every Time, Standard, Full Access, and Custom map visibly onto individual command, file, screen/input, and hardware capabilities.
- **Tailscale is the recommended remote route.** Direct TLS and Hermes Secure Link remain supported; Hermes Reach is marked experimental and stays below supported routes.
### Fixed
- **Detached daemon start reports real readiness.** `daemon start` waits for the spawned PID to authenticate and connect, and reports configuration, authentication, early-exit, and timeout diagnostics instead of returning a false success.
- **Normal tray operation no longer requires opening a CLI for grants.** Pending requests are resolved directly in the focused management dialog.
- **Release checks match the management tray.** CI builds the React assets, validates Tauri metadata, and smoke-tests the packaged tray without obsolete menu-only size or window assertions.
- **Installed tray builds no longer depend on a localhost development server.** Local and packaged builds embed their UI assets, eliminating the `127.0.0.1 refused to connect` failure.
- **Legacy LAN and Tailscale routes no longer appear as Custom VPN.** Route testing infers generic saved roles from the endpoint and reports the correct network path.
- **PowerShell output remains complete.** Scalar, pipeline, JSON, native output, errors, exit status, and truncation metadata return reliably through desktop RPC.
- **Tray placement follows the real notification area.** Responsive geometry uses the tray monitor and DPI and remains anchored above the icon.
## Install
+16 -4
View File
@@ -1,17 +1,28 @@
# Hermes-Relay-Server v__VERSION__
**Release Date:** August 11, 2026
**Release Date:** August 13, 2026
This patch improves gateway recovery diagnostics and prevents clients from reconnecting in lockstep after a shared restart.
This release adds an operator-owned secure ingress path, promotes Tailscale as the easiest supported remote route, and introduces Hermes Reach as a disabled-by-default experimental broker for outbound-only environments.
Standard chat, session history, and Vanilla Hermes voice remain upstream-owned and do not require this plugin.
## What's changed
### Added
- **Hermes Secure Link.** A pinned-TLS ingress can expose Relay, API, and Dashboard namespaces through one self-hosted endpoint while retaining each service's native authentication.
- **Experimental Hermes Reach.** An optional self-hosted rendezvous broker forwards opaque inner Secure Link TLS records, with hashed credentials, replay protection, bounded streams, persistence, and revocation.
- **Remote-access status.** Dashboard and pairing metadata distinguish reachability from transport protection and show supported services without exposing certificate pins.
### Changed
- **Tailscale is recommended for remote access.** Tailscale Serve remains the simplest supported path; direct TLS and Secure Link are self-hosted alternatives, while Reach stays advanced and experimental.
- **Pairing carries reviewed transport trust.** QR payloads include the Secure Link endpoint and pin before the first network request; rotation requires explicit re-pairing.
### Fixed
- **Bounded prior-exit diagnostics.** Relay Doctor and `/relay/info` distinguish a clean stop, an unclean exit, and unknown history, with an optional suspected out-of-memory hint. Raw logs are never returned through the API.
- **Desynchronized recovery.** Ordinary exponential reconnect delays use full jitter so multiple Relay clients do not retry in lockstep after the gateway restarts. Explicit reconnects and server-directed retry timing remain unchanged.
- **Route credentials remain scoped and revocable.** Reach credentials are issued only through trusted Secure Link ingress, replaced atomically per Relay session, bounded by session expiry, and removed on revocation.
- **Proxy namespaces preserve credential isolation.** API and Dashboard headers, cookies, redirects, methods, sizes, timeouts, and loopback authority are constrained independently.
## Install / update
@@ -26,6 +37,7 @@ Standard chat, session history, and Vanilla Hermes voice remain upstream-owned a
## Verify
hermes relay doctor
# Agent/tool callers can use desktop_health to list desktop targets.
python scripts/check-plugin-version-sync.py --expect __VERSION__
---
+15
View File
@@ -70,6 +70,21 @@ an HTTPS reverse proxy. The [full walkthrough](https://hermes-relay.dev/docs/gui
covers Windows, remote access, and dashboard authentication. You do not need to
enable the separate API server or invent an API key for the standard path.
For plugin-enabled setups, optional **Hermes Secure Link** presents Relay, API,
and Dashboard routes through one pairing-pinned TLS origin. It protects traffic
to the paired endpoint while each service keeps its own authentication; it does
not provide reachability or independently identify the physical host. You still
use LAN routing, Tailscale or another VPN, or an operator-managed public route
to reach the listener. Secure Link is off by default and requires a fresh QR
pairing after it is enabled. See the
[remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/).
**Hermes Reach** is an experimental, advanced outbound-broker route. It remains
available for development and self-hosted evaluation, but it is disabled by
default, ordered after supported routes, and not recommended for normal remote
access. Use Tailscale for the easiest supported remote setup, or a public TLS
domain / Direct Secure Link when you want to own the complete network path.
### 3 · Connect and talk
Open the app, choose **Connect to Hermes**, and enter or discover the dashboard
+6 -16
View File
@@ -8,24 +8,14 @@ For shipped work, see `DEVLOG.md`. For architectural decisions, see `docs/decisi
## Structured desktop hardware capabilities
Desktop command, PowerShell, process, and job tools currently execute with the
desktop daemon's OS-user authority. Add typed hardware operations for reliable
schemas, audit detail, and task-scoped approval, but do not present hardware
toggles as isolation while an enabled general shell can reach the same device.
- Define per-host capabilities for commands, files, processes, clipboard,
screen, input, connected devices, microphone, and camera. Disabled must win,
hardware-sensitive capabilities must default off, and unavailable backends
must appear unavailable rather than as inert toggles.
- Add a **Structured only** access profile that withholds shell/process escape
hatches so individual capability toggles become enforceable boundaries.
- Implement connected-device support first with typed, serial-bound ADB
operations (`list`, `shell`, `push`, `pull`, `install`, and bounded logcat)
instead of a generic device-exec wrapper.
Structured access and per-host USB policy now ship with typed, serial-bound ADB
list, shell, push, pull, install, and bounded logcat operations. Remaining work:
- Add microphone and camera only with backend readiness detection, bounded local
grants, active-use indicators, audit events, and immediate cancellation.
- Reconcile legacy `desktop_screenshot` with the task-granted computer screenshot
path so screen capture follows one policy.
- Extend capability policy beyond hardware only where a typed broker provides a
meaningfully stronger boundary than Structured mode already provides.
---
@@ -932,7 +922,7 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
- Live gateway must discover the plugin (`~/.hermes/plugins/hermes-relay` → `plugin/`) and `plugins.enabled` must include `hermes-relay` for the `phone` platform to register. Confirm `phone` appears in `hermes gateway status` with `PHONE_ENABLED=1`.
- End-to-end: with the app paired + "Let Hermes message me" on, run `send_message target=phone text=...` (and a cron `deliver=phone`) and confirm a notification on the device. Verify 503 (no phone) and the off-by-default gates.
- **Phase 2c reply round-trip — ✅ DONE (verified on-device 2026-06-29).** Confirmed: agent → phone notification → inline reply → drained through the relay's loopback `GET /phone/replies` (different process) → `handle_message` (`role_authorized=True`, no `PHONE_ALLOW_ALL_USERS`) → agent answer back in the *same* thread. Both fixes required (see DEVLOG / the Phase 2c bullet above).
- **FIX: cron `deliver=phone` / standalone send is broken.** Live testing: `hermes send --to phone` returns `{"error": "Unknown platform: phone"}`. The standalone (non-gateway) send path doesn't run a `kind=standalone` plugin's programmatic `ctx.register_platform`, so it never learns `phone` — only the running gateway (which loads `register()` at startup) does. The agent path (`send_message target=phone` in the gateway) works and was verified end-to-end on-device; the standalone/cron path needs the platform discoverable there too (declare it so the standalone loader picks it up, or route cron through the gateway). Until then `cron deliver=phone` won't work.
- **Cron `deliver=phone` live certification pending.** The plugin now registers its standalone sender and enumerates the canonical phone home through the upstream adapter channel-directory hook. Re-run the device scenario above on the deployed plugin to certify scheduled delivery, including the offline queue and opt-in gates.
- **FIX SHIPPED (2026-07-07) — installer + doctor guard against stale duplicate plugin copies; live-host verify pending.** Root cause of the 2026-06-29 round-trip failure: the gateway loader dedups discovered plugins by manifest `name`, so a second directory declaring `name: hermes-relay` (an old-installer backup copy, or a stray native install) could win the dedup and make the gateway load stale code — silently ignoring every later deploy. `plugin/doctor.py` now emits a `plugin-name-unique` warning when more than one directory under `~/.hermes/plugins/` declares the same plugin name (distinct real targets only — two links to the same target are deduped), and `install.sh` sweeps any such duplicate so only the canonical `hermes-relay` symlink survives. (Current `install.sh` already `rm -rf`s the old link rather than backing it up inside the plugins dir, so the original "back up outside the plugins dir" half is moot.) **Verify on the live host:** `hermes relay doctor` reports the `plugin-name-unique` check, and a reinstall leaves exactly one `hermes-relay` entry under `~/.hermes/plugins/`.
## Phone platform — usability roadmap (post device-verification, 2026-06-29)
@@ -965,7 +955,7 @@ Phase 1 (end-to-end spine) shipped on `Codename-11/phone-platform` — `send_mes
The gateway-platform model is the *correct + sufficient architecture* (the phone is a registered platform peer, so anything that routes to a platform — `send_message`, cron `deliver=`, channel directory, background jobs — can reach the phone). These are the concrete gaps between "architecturally a peer" and "I never open Discord":
- **Guaranteed background delivery (the biggest gap; no push today).** Delivery is **live-WSS-only** + a 24 h relay buffer; there is **no FCM/UnifiedPush** wake-up. If the app process is dead AND not holding a socket, a message waits for the next reconnect, and the relay buffer is ephemeral (lost on relay restart). Discord/Telegram feel instant because they wake the device via push even when the app is dead. Decide a **push transport**: **UnifiedPush/ntfy** (recommended — self-hostable, no Google dependency, upstream *already* ships an `ntfy` platform, on-brand for self-hosted) vs **FCM** (simplest UX but adds Play Services + a push relay; clashes with self-hosted ethos — at most the `googlePlay` flavor) vs **persistent foreground keep-alive service** holding the relay WSS (zero new infra, like `GatewayKeepAliveService`, but battery cost + Doze-fragile). Likely: UnifiedPush primary + foreground-keepalive fallback.
- **Cron / background-job delivery is BROKEN** (already tracked above): `deliver=phone` standalone path → `Unknown platform: phone`. This is load-bearing for "receiver of crons/background jobs" — fix is required, not optional, for the replacement goal.
- **Cron / background-job delivery needs live certification.** The standalone sender and channel-directory enumeration are implemented; certify `deliver=phone` against a deployed Relay and paired device, including reconnect delivery from the bounded offline queue.
- **Agent-initiated multi-thread creation remains.** The app already renders N
`source=phone` sessions, user-created Threads vary `chat_id`, and replies route
by `chat_id` + `reply_to`. The missing parity is letting the agent open/name a
+1
View File
@@ -324,6 +324,7 @@ dependencies {
// QR Code scanning (ML Kit + CameraX)
implementation(libs.mlkit.barcode)
implementation(libs.zxing.core)
implementation(libs.camera.core)
implementation(libs.camera.camera2)
implementation(libs.camera.lifecycle)
@@ -5,6 +5,10 @@ import android.provider.Settings
import android.util.Log
import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.BrokerEndpoint
import com.hermesandroid.relay.data.hasHermesReach
import com.hermesandroid.relay.data.replaceHermesReachCredential
import com.hermesandroid.relay.data.sameBrokerAuthority
import com.hermesandroid.relay.data.PairingPreferences
import com.hermesandroid.relay.data.Profile
import com.hermesandroid.relay.network.relay.ChannelMultiplexer
@@ -15,6 +19,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -558,6 +563,12 @@ class AuthManager(
* Either way, we leave the previously-persisted list untouched.
*/
private var pendingEndpoints: List<EndpointCandidate>? = null
private var activeEndpointProvider: () -> EndpointCandidate? = { null }
/** Bind auth.ok route credentials to the transport that actually carried them. */
fun setActiveEndpointProvider(provider: () -> EndpointCandidate?) {
activeEndpointProvider = provider
}
/**
* Server-advertised agent profiles from the `auth.ok` payload's
@@ -1042,6 +1053,7 @@ class AuthManager(
}
if (token != null) {
applyBrokerRouteCredential(payload)
val s = store()
s.putString(KEY_SESSION_TOKEN, token)
val refreshToken = payload["refresh_token"]
@@ -1150,6 +1162,40 @@ class AuthManager(
}
}
private suspend fun applyBrokerRouteCredential(payload: JsonObject) {
val active = activeEndpointProvider()?.takeIf { it.hasHermesReach() } ?: return
val current = active.broker ?: return
// Fresh pairing is scoped by pendingEndpoints; reconnect rotation is
// accepted only by this connection-scoped AuthManager's live session.
if (pendingEndpoints == null && _authState.value !is AuthState.Paired) return
val credential = payload["route_credential"] as? JsonObject ?: return
if (credential["kind"]?.jsonPrimitive?.contentOrNull != "broker_route") return
val brokerUrl = credential["broker_url"]?.jsonPrimitive?.contentOrNull ?: return
val hostId = credential["host_id"]?.jsonPrimitive?.contentOrNull ?: return
if (!sameBrokerAuthority(brokerUrl, current.url) || hostId != current.hostId) {
Log.w(TAG, "Ignoring broker route credential that does not match the active paired route")
return
}
val replacement = BrokerEndpoint(
url = current.url,
protocolVersion = current.protocolVersion,
hostId = current.hostId,
credentialKind = "route",
token = credential["token"]?.jsonPrimitive?.contentOrNull ?: return,
expiresAt = credential["expires_at"]?.jsonPrimitive?.longOrNull,
)
val validated = active.copy(broker = replacement).takeIf { it.hasHermesReach() } ?: return
val deviceId = getDeviceId()
val source = pendingEndpoints
?: PairingPreferences.getDeviceEndpoints(context, deviceId).first()
val updated = replaceHermesReachCredential(source, current, validated)
if (updated == source) return
if (pendingEndpoints != null) pendingEndpoints = updated
else PairingPreferences.setDeviceEndpoints(context, deviceId, updated)
Log.i(TAG, "Accepted a durable Hermes Reach route credential for the active paired route")
}
private fun handleAuthFail(envelope: Envelope) {
try {
val rawReason = envelope.payload["reason"]?.jsonPrimitive?.contentOrNull
@@ -90,12 +90,28 @@ class CertPinStore(private val context: Context) {
if (pins.isEmpty()) return CertificatePinner.DEFAULT
val builder = CertificatePinner.Builder()
for ((hostPort, pin) in pins) {
val host = hostPort.substringBefore(':')
val host = hostPort.substringBeforeLast(':')
builder.add(host, pin)
}
return builder.build()
}
/**
* Build a pinner for one exact URL authority. CertificatePinner keys by
* hostname only, so adding every stored host:port entry to one client
* accidentally lets a pin learned on one port govern another port.
*/
fun buildPinnerSnapshotFor(url: String): CertificatePinner {
val hostPort = hostPortFromUrl(url) ?: return CertificatePinner.DEFAULT
val pin = getPinsBlocking()[hostPort] ?: return CertificatePinner.DEFAULT
val host = runCatching { URI(url.trim()).host }.getOrNull()
?.takeIf { it.isNotBlank() }
?: return CertificatePinner.DEFAULT
return CertificatePinner.Builder()
.add(host, pin)
.build()
}
/**
* Record a pin for a host. Called from the WebSocket listener's `onOpen`
* when we have a successful connection and can read the peer certs from
@@ -141,6 +141,12 @@ data class ChatMessage(
* through `copy`, while [id] remains the authoritative lookup/wire id.
*/
val uiKey: String = id,
/**
* Durable Gateway transcript row identity for rewind/edit-regenerate.
* This is server-owned and can change after a truncating rewrite; it is
* never used as a Compose key or synthesized client-side.
*/
val rowId: Long? = null,
/**
* Mixture-of-Agents advisor responses surfaced during the live turn.
* Unavailable advisors retain only neutral state, never their raw failure
@@ -421,6 +427,14 @@ data class ChatSession(
/** Durable upstream session metadata, scoped by the owning connection/profile DB. */
val pinned: Boolean = false,
val archived: Boolean = false,
/** Optional newer-upstream workspace context; absent on legacy/API-only hosts. */
val workingDirectory: String? = null,
val gitBranch: String? = null,
val gitRepoRoot: String? = null,
val pullRequestNumber: Int? = null,
val pullRequestUrl: String? = null,
val pullRequestState: String? = null,
val pullRequestDraft: Boolean = false,
) {
val activityTimestamp: Long
get() = firstPositive(lastActivityAt, updatedAt, startedAt)
@@ -129,6 +129,7 @@ data class ChatTurnAskCheckpoint(
val requestId: String? = null,
val text: String,
val choices: List<String>? = null,
val multiSelect: Boolean = false,
val smartDenied: Boolean = false,
val envVar: String? = null,
val timeoutSeconds: Int,
@@ -14,6 +14,9 @@ data class DashboardConnectionStatus(
val gatewayTicketAvailable: Boolean? = null,
val message: String? = null,
val gatewayMode: String? = null,
/** Profiles positively advertised by the live multiplex gateway. */
val servedProfiles: List<String> = emptyList(),
/** Installed profiles reported by the dashboard; never routing authority. */
val profiles: List<String> = emptyList(),
)
@@ -63,12 +63,8 @@ fun EndpointCandidate?.isEncryptedOverlayRoute(isTailscaleDetected: Boolean): Bo
val hint = security.orEmpty().lowercase()
return r == "tailscale" ||
(isTailscaleDetected && hint.contains("tailscale")) ||
r == "plugin_proxy" ||
r == "plugin-proxy" ||
hasSecureProxy() ||
hint.contains("wireguard") ||
hint.contains("https") ||
hint.contains("tls")
(!hasSecureProxy() && (hint.contains("https") || hint.contains("tls")))
}
/** Human label for the overlay mechanism encrypting a route. */
@@ -78,7 +74,6 @@ fun EndpointCandidate?.overlayMechanism(isTailscaleDetected: Boolean): String {
val hint = security.orEmpty().lowercase()
return when {
r == "tailscale" || (isTailscaleDetected && hint.contains("tailscale")) -> "Tailscale"
r == "plugin_proxy" || r == "plugin-proxy" || hasSecureProxy() -> "Proxy"
hint.contains("wireguard") -> "WireGuard"
hint.contains("https") || hint.contains("tls") -> "TLS"
else -> "Encrypted"
@@ -92,7 +87,10 @@ fun classifySurfaceSecurity(
activeEndpoint: EndpointCandidate?,
isTailscaleDetected: Boolean,
): SurfaceSecurity {
val secureLinkProtected = activeEndpoint.secureLinkProtects(label, url)
val (kind, mechanism) = when {
secureLinkProtected -> SurfaceSecurityKind.Tls to
if (activeEndpoint?.hasHermesReach() == true) "Hermes Reach" else "Hermes Secure Link"
isTlsUrl(url) -> SurfaceSecurityKind.Tls to "TLS"
activeEndpoint.isEncryptedOverlayRoute(isTailscaleDetected) ->
SurfaceSecurityKind.Overlay to activeEndpoint.overlayMechanism(isTailscaleDetected)
@@ -101,6 +99,33 @@ fun classifySurfaceSecurity(
return SurfaceSecurity(label = label, kind = kind, mechanism = mechanism, url = url)
}
private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): Boolean {
val candidate = this ?: return false
val routes = candidate.proxy?.takeIf { candidate.hasSecureProxy() }
?.let { proxy ->
val base = proxy.url.trim().trimEnd('/')
Triple(
"$base/dashboard",
"$base/api",
"wss://${base.substringAfter("://")}/relay/ws",
)
} ?: return false
val normalized = url.trim().trimEnd('/')
val service = when (label) {
"Chat & Manage" -> "dashboard"
"API / sessions" -> "api"
"Relay tools" -> "relay"
else -> return false
}
if (service !in candidate.secureLinkServices()) return false
val expected = when (service) {
"dashboard" -> routes.first
"api" -> routes.second
else -> routes.third
}
return normalized.equals(expected, ignoreCase = true)
}
/**
* Roll up the per-surface verdicts into one connection-level [ConnectionSecurity].
* Pure + side-effect free so it is unit-testable without Android.
@@ -45,8 +45,13 @@ data class EndpointCandidate(
val relay: RelayEndpoint? = null,
val dashboard: DashboardEndpoint? = null,
val proxy: ProxyEndpoint? = null,
/** Optional outbound rendezvous carrying the pinned [proxy] byte stream. */
val broker: BrokerEndpoint? = null,
val security: String? = null,
val recommended: Boolean = false,
val experimental: Boolean = false,
@SerialName("display_name")
val displayName: String? = null,
)
/**
@@ -110,6 +115,27 @@ data class ProxyEndpoint(
val transportHint: String? = null,
@SerialName("pin_sha256")
val pinSha256: String? = null,
/** Independently authenticated services carried by this pinned origin. */
val surfaces: List<String> = listOf("relay"),
)
/**
* Hermes Reach rendezvous metadata from an operator-reviewed pairing payload.
* The token authenticates only this broker route; Hermes service credentials
* remain inside the QR-pinned Secure Link TLS connection.
*/
@Serializable
data class BrokerEndpoint(
val url: String,
@SerialName("protocol_version")
val protocolVersion: Int = 1,
@SerialName("host_id")
val hostId: String,
@SerialName("credential_kind")
val credentialKind: String,
val token: String,
@SerialName("expires_at")
val expiresAt: Long? = null,
)
/**
@@ -123,7 +149,7 @@ data class ProxyEndpoint(
*/
fun EndpointCandidate.isKnownRole(): Boolean {
return when (role.lowercase()) {
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "https" -> true
"lan", "tailscale", "public", "plugin_proxy", "plugin-proxy", "outbound_broker", "https" -> true
else -> false
}
}
@@ -146,7 +172,8 @@ fun EndpointCandidate.displayLabel(): String {
"Public"
}
"https" -> "HTTPS"
"plugin_proxy", "plugin-proxy" -> "Plugin proxy"
"plugin_proxy", "plugin-proxy" -> "Hermes Secure Link"
"outbound_broker", "broker", "relay_broker" -> "Hermes Reach · Experimental"
else -> "Custom VPN ($role)"
}
}
@@ -177,7 +204,69 @@ fun EndpointCandidate.routeAuthority(): String? {
}
fun EndpointCandidate.hasSecureProxy(): Boolean =
proxy?.url?.startsWith("https://", ignoreCase = true) == true ||
proxy?.url?.startsWith("wss://", ignoreCase = true) == true ||
role.equals("plugin_proxy", ignoreCase = true) ||
role.equals("plugin-proxy", ignoreCase = true)
proxy?.isValidPinnedProxy() == true
/** Product-facing service inventory; wire identifiers remain unchanged. */
fun EndpointCandidate.secureLinkServices(): List<String> =
if (!hasSecureProxy()) emptyList() else proxy.orEmptySurfaces()
fun EndpointCandidate.secureLinkCoversAllServices(): Boolean =
secureLinkServices().containsAll(listOf("relay", "api", "dashboard"))
fun EndpointCandidate.presentationRouteUrl(): String? =
broker?.url?.takeIf { hasHermesReach() } ?: proxy?.url?.takeIf { hasSecureProxy() } ?: primaryRouteUrl()
fun EndpointCandidate.hasHermesReach(): Boolean =
role.lowercase() in setOf("outbound_broker", "broker", "relay_broker") &&
broker?.isValidHermesReach() == true && hasSecureProxy()
fun BrokerEndpoint.isValidHermesReach(): Boolean {
if (protocolVersion != 1 || !hostId.isCanonicalBase64Url(16) || !token.isCanonicalBase64Url(32)) return false
if (credentialKind !in setOf("bootstrap", "route")) return false
if (credentialKind == "bootstrap" && expiresAt?.let { it <= System.currentTimeMillis() / 1000L } == true) return false
val uri = runCatching { URI(url.trim()) }.getOrNull() ?: return false
if (!uri.scheme.equals("wss", ignoreCase = true) || uri.host.isNullOrBlank()) return false
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return false
return uri.rawPath.orEmpty().let { it.isEmpty() || it == "/" || it == "/v1/connect" }
}
private fun String.isCanonicalBase64Url(byteCount: Int): Boolean {
if (isBlank() || '=' in this) return false
val decoded = runCatching { java.util.Base64.getUrlDecoder().decode(this) }.getOrNull() ?: return false
return decoded.size == byteCount &&
java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(decoded) == this
}
/** Exact host locator + broker authority replacement; never crosses devices. */
internal fun replaceHermesReachCredential(
source: List<EndpointCandidate>,
expected: BrokerEndpoint,
replacement: EndpointCandidate,
): List<EndpointCandidate> = source.map { candidate ->
if (candidate.broker?.hostId == expected.hostId &&
sameBrokerAuthority(candidate.broker.url, expected.url)
) replacement else candidate
}
internal fun sameBrokerAuthority(left: String, right: String): Boolean = runCatching {
val a = URI(left.trim())
val b = URI(right.trim())
fun port(uri: URI) = if (uri.port > 0) uri.port else 443
a.scheme.equals("wss", true) && b.scheme.equals("wss", true) &&
a.host.equals(b.host, true) && port(a) == port(b) &&
a.rawPath.orEmpty().trimEnd('/') == b.rawPath.orEmpty().trimEnd('/')
}.getOrDefault(false)
private fun ProxyEndpoint?.orEmptySurfaces(): List<String> = this?.surfaces.orEmpty()
.map { it.trim().lowercase() }
.filter { it in setOf("relay", "api", "dashboard") }
.distinct()
fun ProxyEndpoint.isValidPinnedProxy(): Boolean {
val uri = runCatching { URI(url.trim().trimEnd('/')) }.getOrNull() ?: return false
if (!uri.scheme.equals("https", ignoreCase = true) || uri.host.isNullOrBlank()) return false
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return false
if (uri.rawPath.orEmpty().let { it.isNotEmpty() && it != "/" }) return false
val pin = pinSha256?.trim()?.removePrefix("sha256/") ?: return false
return runCatching { java.util.Base64.getDecoder().decode(pin).size == 32 }.getOrDefault(false)
}
@@ -2,6 +2,8 @@ package com.hermesandroid.relay.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
/**
* A rich content card emitted inline in an assistant message via the
@@ -117,6 +119,8 @@ data class HermesCardInput(
val kind: String,
/** Quick-answer chips (clarify). Empty = no chip row. */
val choices: List<String> = emptyList(),
/** Choices toggle independently and require an explicit submit. */
val multiSelect: Boolean = false,
/** Render the inline free-text mini field under the chips. */
val allowFreeText: Boolean = false,
/** Password-style field: masked glyphs + reveal toggle (secret/sudo). */
@@ -124,7 +128,7 @@ data class HermesCardInput(
/** Submit is a 650ms hold-to-confirm press-fill instead of a tap (sudo). */
val holdToConfirm: Boolean = false,
/**
* Wall-clock expiry for timed asks (sudo 120s, clarify/secret 300s).
* Wall-clock expiry for asks with an advertised deadline.
* The renderer shows a countdown footer (Amber under 30s) and
* self-collapses to "Expired — not granted" past it. Null = no timeout
* (approval is session-scoped).
@@ -155,6 +159,10 @@ data class HermesCardInput(
}
}
/** Exact JSON-array wire value expected by upstream multi-select clarify. */
internal fun encodeClarifyMultiSelectAnswer(values: List<String>): String =
Json.encodeToString(values.map(String::trim).filter(String::isNotEmpty).distinct())
/**
* A label/value row inside a card. [value] is rendered as markdown so the
* agent can embed emphasis, inline code, or links.
@@ -136,3 +136,91 @@ data class ProfileMemoryUpdateResponse(
@SerialName("bytes_written")
val bytesWritten: Long,
)
/** Authoritative upstream `profiles.describe` snapshot. */
data class GatewayProfileDescription(
val name: String,
val description: String,
val soul: String,
val provider: String,
val model: String,
val skills: List<GatewayProfileSkill>,
val toolsets: List<GatewayProfileToolset>,
val toolsetsPinned: Boolean,
)
data class GatewayProfileSkill(val name: String, val enabled: Boolean)
data class GatewayProfileToolset(
val name: String,
val description: String,
val toolCount: Int,
val enabled: Boolean,
)
enum class GatewayProfileSection(val wireName: String) {
Description("description"),
Soul("soul"),
Model("model"),
Skills("skills"),
Toolsets("toolsets"),
}
/** Null leaves a section unchanged; empty lists retain upstream replace semantics. */
data class GatewayProfilePatch(
val description: String? = null,
val soul: String? = null,
val provider: String? = null,
val model: String? = null,
val disabledSkills: List<String>? = null,
val enabledToolsets: List<String>? = null,
) {
val requestedSections: Set<GatewayProfileSection>
get() = buildSet {
if (description != null) add(GatewayProfileSection.Description)
if (soul != null) add(GatewayProfileSection.Soul)
if (provider != null && model != null) add(GatewayProfileSection.Model)
if (disabledSkills != null) add(GatewayProfileSection.Skills)
if (enabledToolsets != null) add(GatewayProfileSection.Toolsets)
}
}
data class GatewayProfileConfigureResult(
val requested: Set<GatewayProfileSection>,
val applied: Set<GatewayProfileSection>,
) {
val failed: Set<GatewayProfileSection> get() = requested - applied
}
interface GatewayProfileEditorClient {
suspend fun describeProfile(profileName: String): Result<GatewayProfileDescription>
suspend fun configureProfile(
profileName: String,
patch: GatewayProfilePatch,
): Result<GatewayProfileConfigureResult>
}
class GatewayProfileEditorUnsupportedException : Exception(
"Profile editing is not supported by this gateway",
)
/** Relay fallback retained for older gateways and Relay-only memory files. */
interface LegacyProfileInspectorClient {
suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse>
suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse>
suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse>
suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse>
suspend fun updateSoul(profileName: String, content: String): Result<ProfileSoulUpdateResponse>
suspend fun updateMemoryEntry(
profileName: String,
filename: String,
content: String,
): Result<ProfileMemoryUpdateResponse>
suspend fun updateSkillToggle(skillName: String, enabled: Boolean): Result<RelaySkillToggleResult>
suspend fun probeSkillToggleSupported(): Boolean
}
sealed interface RelaySkillToggleResult {
data object Ok : RelaySkillToggleResult
data object NotImplemented : RelaySkillToggleResult
}
@@ -12,6 +12,7 @@ import com.hermesandroid.relay.auth.CertPinStore
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.primaryRouteUrl
import com.hermesandroid.relay.data.PairingPreferences
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
import com.hermesandroid.relay.diagnostics.DiagnosticSeverity
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
@@ -77,6 +78,9 @@ internal fun buildRelayRequestOrNull(url: String): Request? =
null
}
private fun EndpointCandidate.relayWebSocketUrl(): String? =
pluginProxyRoutesOrNull()?.relayWebSocketUrl ?: relay?.url
class ConnectionManager(
private val multiplexer: ChannelMultiplexer,
/**
@@ -142,6 +146,8 @@ class ConnectionManager(
private val deviceIdProvider: (suspend () -> String?)? = null,
/** Random source for ordinary reconnect full-jitter; exact backoffs never use it. */
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
/** Exact-authority pinned client for a plugin-proxy WSS URL. */
private val proxyClientProvider: ((String) -> OkHttpClient?)? = null,
) {
private val supervisorJob = SupervisorJob()
private val scope = CoroutineScope(supervisorJob + Dispatchers.IO)
@@ -151,7 +157,7 @@ class ConnectionManager(
encodeDefaults = true
}
private fun buildClient(): OkHttpClient {
private fun buildClient(url: String? = null): OkHttpClient {
val builder = OkHttpClient.Builder()
// OkHttp's 10s default connectTimeout is LAN-tuned; a Tailscale
// DERP-relayed cold-start handshake can exceed it, and a failed
@@ -165,7 +171,9 @@ class ConnectionManager(
// that wipes a pin would still be subject to the pre-wipe rules.
certPinStore?.let { store ->
try {
builder.certificatePinner(store.buildPinnerSnapshot())
builder.certificatePinner(
url?.let(store::buildPinnerSnapshotFor) ?: store.buildPinnerSnapshot(),
)
} catch (e: Exception) {
Log.w(TAG, "CertificatePinner build failed: ${e.message}")
builder.certificatePinner(CertificatePinner.DEFAULT)
@@ -224,10 +232,12 @@ class ConnectionManager(
// Endpoints card in Settings.
private val _activeEndpoint = MutableStateFlow<EndpointCandidate?>(null)
val activeEndpoint: StateFlow<EndpointCandidate?> = _activeEndpoint.asStateFlow()
private val _activeApiEndpoint = MutableStateFlow<EndpointCandidate?>(null)
val activeApiEndpoint: StateFlow<EndpointCandidate?> = _activeApiEndpoint.asStateFlow()
/** Relay-only winner, deliberately separate from the standard route. */
@Volatile
private var activeRelayEndpoint: EndpointCandidate? = null
private val _activeRelayEndpoint = MutableStateFlow<EndpointCandidate?>(null)
val activeRelayEndpoint: StateFlow<EndpointCandidate?> = _activeRelayEndpoint.asStateFlow()
/**
* Manual role override. When non-null, the resolver's output is replaced
@@ -348,11 +358,14 @@ class ConnectionManager(
// behavior for freshly-upgraded installs and for v1/v2 QRs where
// the synthesized list just collapses to the same URL anyway.
scope.launch {
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
val resolvedRelayUrl = relayResolved?.relay?.url?.takeIf { it.isNotBlank() }
val resolvedRelayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
val targetUrl = resolvedRelayUrl ?: url.takeIf { it.isNotBlank() }
activeRelayEndpoint = relayResolved
_activeRelayEndpoint.value = relayResolved
_activeApiEndpoint.value = apiResolved
if (resolved != null) {
_activeEndpoint.value = resolved
Log.i(TAG, "connect: standard resolver picked role=${resolved.role} " +
@@ -379,7 +392,7 @@ class ConnectionManager(
Log.i(
TAG,
"connect: relay resolver picked role=${relayRoute.role} " +
"url=${relayRoute.relay?.url}",
"url=${relayRoute.relayWebSocketUrl()}",
)
}
if (targetUrl != null) {
@@ -534,7 +547,8 @@ class ConnectionManager(
* for any reason we don't block the connect loop forever.
*/
suspend fun resolveBestEndpoint(): EndpointCandidate? =
resolveBestEndpointSafe(EndpointSurface.Standard)
resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
private suspend fun resolveBestEndpointSafe(
surface: EndpointSurface,
@@ -612,7 +626,9 @@ class ConnectionManager(
suspend fun probeAndReconnectNow(): EndpointCandidate? {
endpointResolver?.clearCache()
val current = serverUrl
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
// Transient probe miss while the relay socket is demonstrably up
@@ -621,8 +637,9 @@ class ConnectionManager(
return _activeEndpoint.value
}
_activeEndpoint.value = resolved
if (relayResolved != null) activeRelayEndpoint = relayResolved
val targetUrl = relayResolved?.relay?.url ?: current ?: return resolved
_activeApiEndpoint.value = apiResolved
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
val targetUrl = relayResolved?.relayWebSocketUrl() ?: current ?: return resolved
val normalizedTarget = normalizeRelayUrl(targetUrl)
// Reconnect when the winner changed, and also when the socket is
// stale/disconnected on the same winner. The latter makes the
@@ -659,7 +676,9 @@ class ConnectionManager(
*/
suspend fun refreshActiveEndpoint(clearProbeCache: Boolean = false): EndpointCandidate? {
if (clearProbeCache) endpointResolver?.clearCache()
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
if (resolved == null && _connectionState.value == ConnectionState.Connected) {
// Transient probe miss while the relay socket is demonstrably up
// (slow resume, mid-handoff blip) — keep publishing the live
@@ -668,6 +687,7 @@ class ConnectionManager(
return _activeEndpoint.value
}
_activeEndpoint.value = resolved
_activeApiEndpoint.value = apiResolved
return resolved
}
@@ -684,7 +704,7 @@ class ConnectionManager(
fun getManualRoleOverride(): String? = _manualRoleOverride.value
private fun markActiveRelayEndpointUnreachable(reason: String) {
val active = activeRelayEndpoint ?: return
val active = _activeRelayEndpoint.value ?: return
endpointResolver?.markUnreachable(active, EndpointSurface.Relay)
Log.i(TAG, "marked endpoint role=${active.role} unreachable ($reason)")
}
@@ -710,7 +730,9 @@ class ConnectionManager(
// manages its own cache (clear + markUnreachable) and passes false.
if (wipeCache) endpointResolver.clearCache()
val current = serverUrl
val resolved = resolveBestEndpointSafe(EndpointSurface.Standard)
val resolved = resolveBestEndpointSafe(EndpointSurface.Dashboard)
?: resolveBestEndpointSafe(EndpointSurface.Standard)
val apiResolved = resolveBestEndpointSafe(EndpointSurface.Api)
if (resolved == null) {
// Hysteresis for the AUTOMATIC (network-callback) path. A
// transient cold-route probe miss must NOT null the published
@@ -747,6 +769,7 @@ class ConnectionManager(
}
sustainedLossDeclared = false
_activeEndpoint.value = resolved
_activeApiEndpoint.value = apiResolved
if (current == null) return@launch
// After an explicit disconnect() the route still publishes above
// (HTTP surfaces keep roaming), but no socket action: without
@@ -756,8 +779,8 @@ class ConnectionManager(
// the swap path never re-checked it.)
if (!shouldReconnect) return@launch
val relayResolved = resolveBestEndpointSafe(EndpointSurface.Relay)
if (relayResolved != null) activeRelayEndpoint = relayResolved
val relayUrl = relayResolved?.relay?.url?.takeIf { it.isNotBlank() }
if (relayResolved != null) _activeRelayEndpoint.value = relayResolved
val relayUrl = relayResolved?.relayWebSocketUrl()?.takeIf { it.isNotBlank() }
?: return@launch
if (isRelayRateLimitBackoffActive(
rateLimitBackoffUntilMs,
@@ -902,7 +925,8 @@ class ConnectionManager(
// the ViewModel on the next connection load.
_manualRoleOverride.value = null
_activeEndpoint.value = null
activeRelayEndpoint = null
_activeApiEndpoint.value = null
_activeRelayEndpoint.value = null
reconnectState.reset()
}
@@ -982,7 +1006,18 @@ class ConnectionManager(
// Every new socket starts unauthenticated — the send-gate stays closed
// (auth frame excepted) until this socket's own auth.ok arrives.
authenticated = false
client = buildClient()
val isPluginProxyUrl = _activeRelayEndpoint.value?.pluginProxyRoutesOrNull()
?.relayWebSocketUrl
?.equals(url, ignoreCase = true) == true
client = if (isPluginProxyUrl) {
proxyClientProvider?.invoke(url) ?: run {
Log.e(TAG, "Pinned plugin proxy client unavailable — refusing generic TLS fallback")
_connectionState.value = ConnectionState.Disconnected
return
}
} else {
buildClient(url)
}
val request = buildRelayRequestOrNull(url)
if (request == null) {
@@ -1240,7 +1275,7 @@ class ConnectionManager(
// during the retry window).
if (shouldReconnect && reconnectGate()) {
val resolved = resolveBestEndpointSafe(EndpointSurface.Relay)
val targetUrl = resolved?.relay?.url
val targetUrl = resolved?.relayWebSocketUrl()
if (resolved != null) {
// Mirror scheduleNetworkReResolve: clear the sustained-loss
// latch on a successful resolve so a later transient miss
@@ -1248,7 +1283,7 @@ class ConnectionManager(
// in onLost's grace job but can be cleared on EITHER success
// edge — network-callback or relay-timer.)
sustainedLossDeclared = false
activeRelayEndpoint = resolved
_activeRelayEndpoint.value = resolved
}
if (targetUrl != null && normalizeRelayUrl(targetUrl) != url) {
Log.i(TAG, "scheduleReconnect: switching $url → ${normalizeRelayUrl(targetUrl)}")
@@ -7,6 +7,8 @@ import com.hermesandroid.relay.data.ProfileSkillsResponse
import com.hermesandroid.relay.data.ProfileSoulResponse
import com.hermesandroid.relay.data.ProfileSoulUpdateResponse
import com.hermesandroid.relay.data.ProfileMemoryUpdateResponse
import com.hermesandroid.relay.data.LegacyProfileInspectorClient
import com.hermesandroid.relay.data.RelaySkillToggleResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerializationException
@@ -48,7 +50,7 @@ class RelayProfileInspectorClient(
private val okHttpClient: OkHttpClient,
private val relayUrlProvider: () -> String?,
private val sessionTokenProvider: suspend () -> String?,
) {
) : LegacyProfileInspectorClient {
companion object {
private const val TAG = "RelayProfileInspector"
@@ -79,19 +81,19 @@ class RelayProfileInspectorClient(
/** Fetch `GET /api/profiles/{name}/config`. */
suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> =
override suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> =
get(profileName, "config", ProfileConfigResponse.serializer())
/** Fetch `GET /api/profiles/{name}/skills`. */
suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse> =
override suspend fun fetchSkills(profileName: String): Result<ProfileSkillsResponse> =
get(profileName, "skills", ProfileSkillsResponse.serializer())
/** Fetch `GET /api/profiles/{name}/soul`. */
suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse> =
override suspend fun fetchSoul(profileName: String): Result<ProfileSoulResponse> =
get(profileName, "soul", ProfileSoulResponse.serializer())
/** Fetch `GET /api/profiles/{name}/memory`. */
suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse> =
override suspend fun fetchMemory(profileName: String): Result<ProfileMemoryResponse> =
get(profileName, "memory", ProfileMemoryResponse.serializer())
/**
@@ -108,7 +110,7 @@ class RelayProfileInspectorClient(
* would be a protocol violation; we send empty-string for an empty
* SOUL.
*/
suspend fun updateSoul(
override suspend fun updateSoul(
profileName: String,
content: String,
): Result<ProfileSoulUpdateResponse> = withContext(Dispatchers.IO) {
@@ -137,7 +139,7 @@ class RelayProfileInspectorClient(
* Used for both creating a new memory entry (the relay writes the
* file if missing) and updating an existing entry.
*/
suspend fun updateMemoryEntry(
override suspend fun updateMemoryEntry(
profileName: String,
filename: String,
content: String,
@@ -270,10 +272,10 @@ class RelayProfileInspectorClient(
* server" snackbar and ghost out the toggle. When the real
* implementation lands server-side, this method needs no change.
*/
suspend fun updateSkillToggle(
override suspend fun updateSkillToggle(
skillName: String,
enabled: Boolean,
): Result<SkillToggleResult> = withContext(Dispatchers.IO) {
): Result<RelaySkillToggleResult> = withContext(Dispatchers.IO) {
val relayUrl = relayUrlProvider()?.trim().orEmpty()
if (relayUrl.isEmpty()) {
return@withContext Result.failure(
@@ -319,8 +321,8 @@ class RelayProfileInspectorClient(
try {
okHttpClient.newCall(request).execute().use { response ->
when (response.code) {
in 200..299 -> Result.success(SkillToggleResult.Ok)
501 -> Result.success(SkillToggleResult.NotImplemented)
in 200..299 -> Result.success(RelaySkillToggleResult.Ok)
501 -> Result.success(RelaySkillToggleResult.NotImplemented)
401, 403 -> Result.failure(
IOException("Unauthorized — re-pair with the relay")
)
@@ -348,7 +350,7 @@ class RelayProfileInspectorClient(
* "not implemented" and any 2xx as "supported". The relay serves
* OPTIONS via aiohttp's CORS handling by default.
*/
suspend fun probeSkillToggleSupported(): Boolean = withContext(Dispatchers.IO) {
override suspend fun probeSkillToggleSupported(): Boolean = withContext(Dispatchers.IO) {
val relayUrl = relayUrlProvider()?.trim().orEmpty()
if (relayUrl.isEmpty()) return@withContext false
val sessionToken = sessionTokenProvider() ?: return@withContext false
@@ -402,11 +404,6 @@ class RelayProfileInspectorClient(
* answered 501 — not implemented yet" without inventing magic
* error strings.
*/
sealed class SkillToggleResult {
data object Ok : SkillToggleResult()
data object NotImplemented : SkillToggleResult()
}
/**
* Best-effort pull of a `detail` or `error` string out of a relay
* 400 body. Falls back to the first 120 chars of the payload when
@@ -55,6 +55,8 @@ data class RouteProbeOutcome(
*/
enum class EndpointSurface {
Standard,
Dashboard,
Api,
Relay,
}
@@ -109,6 +111,8 @@ class EndpointResolver(
* expected path for plain JVM tests.
*/
private val context: Context? = null,
/** Route-aware client for pinned plugin proxy probes. */
private val clientForCandidate: ((EndpointCandidate) -> OkHttpClient?)? = null,
) {
/**
@@ -196,8 +200,13 @@ class EndpointResolver(
val authority = when (surface) {
EndpointSurface.Standard ->
candidate.routeAuthority() ?: candidate.primaryRouteUrl().orEmpty().lowercase()
EndpointSurface.Dashboard ->
routeAuthority(candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl ?: candidate.dashboard?.url).orEmpty()
EndpointSurface.Api ->
routeAuthority(candidate.pluginProxyRoutesOrNull()?.apiBaseUrl ?: candidate.api?.url).orEmpty()
EndpointSurface.Relay ->
routeAuthority(candidate.relay?.url).orEmpty()
candidate.pluginProxyRoutesOrNull()?.authority
?: routeAuthority(candidate.relay?.url).orEmpty()
}
return "${surface.name.lowercase()}|${candidate.role}|$authority"
}
@@ -239,11 +248,16 @@ class EndpointResolver(
val eligible = candidates.filter { probeTarget(it, surface) != null }
if (eligible.isEmpty()) return null
// Strict priority: sort ascending so priority-0 lands first. Grouping
// preserves emitted order within a priority class (DNS SRV parity).
val groups = eligible.groupBy { it.priority }.toSortedMap()
// Supported routes always run before experimental routes. Priority is
// strict inside each stability tier, so Reach remains available as a
// last-resort fallback without displacing Tailscale or direct TLS.
val supported = eligible.filterNot { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
val experimental = eligible.filter { it.experimental || it.role.equals("outbound_broker", ignoreCase = true) }
val groups = (supported.groupBy { it.priority }.toSortedMap().values +
experimental.groupBy { it.priority }.toSortedMap().values)
for ((priority, group) in groups) {
for (group in groups) {
val priority = group.first().priority
Log.d(TAG, "probing priority=$priority group (size=${group.size})")
val winner = raceGroup(group, surface)
if (winner != null) {
@@ -356,6 +370,8 @@ class EndpointResolver(
val startedAtMs = clock()
val operation = when (surface) {
EndpointSurface.Standard -> "Dashboard or API route health probe"
EndpointSurface.Dashboard -> "Dashboard route health probe"
EndpointSurface.Api -> "API route health probe"
EndpointSurface.Relay -> "Relay route health probe"
}
val target = probeTarget(candidate, surface)
@@ -375,7 +391,7 @@ class EndpointResolver(
recordOutcome(candidate, surface, reachable = false, detail = "Invalid route URL")
return false
}
val fastClient = httpClient.newBuilder()
val fastClient = (clientForCandidate?.invoke(candidate) ?: httpClient).newBuilder()
.connectTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.readTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
.writeTimeout(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
@@ -480,6 +496,29 @@ class EndpointResolver(
candidate: EndpointCandidate,
surface: EndpointSurface,
): ProbeTarget? {
if (surface == EndpointSurface.Dashboard) {
candidate.pluginProxyRoutesOrNull()?.dashboardBaseUrl?.let { base ->
return ProbeTarget(base, "$base/api/status", "/dashboard/api/status")
}
candidate.dashboard?.url?.trim()?.trimEnd('/')?.takeIf { it.isNotBlank() }?.let { base ->
return ProbeTarget(base, "$base/api/status", "/api/status")
}
return null
}
if (surface == EndpointSurface.Api) {
candidate.pluginProxyRoutesOrNull()?.apiBaseUrl?.let { base ->
return ProbeTarget(base, "$base/health", "/api/health")
}
candidate.api?.url?.let { base -> return ProbeTarget(base, "$base/health", "/health") }
return null
}
if (surface == EndpointSurface.Relay) candidate.pluginProxyRoutesOrNull()?.let { proxy ->
return ProbeTarget(
baseUrl = proxy.relayHttpUrl,
requestUrl = "${proxy.relayHttpUrl}/health",
path = "/relay/health",
)
}
if (surface == EndpointSurface.Relay) {
return relayProbeTarget(candidate)
}
@@ -529,6 +568,11 @@ class EndpointResolver(
return null
}
internal fun probeRequestUrlForTest(
candidate: EndpointCandidate,
surface: EndpointSurface,
): String? = probeTarget(candidate, surface)?.requestUrl
/**
* Map a probe exception to a short, actionable string for the Routes
* card. The TLS case is the headline: a route saved with `https://`
@@ -546,6 +590,8 @@ class EndpointResolver(
private fun EndpointSurface.diagnosticTarget(): String = when (this) {
EndpointSurface.Standard -> "Dashboard or API server"
EndpointSurface.Dashboard -> "Dashboard"
EndpointSurface.Api -> "API server"
EndpointSurface.Relay -> "Relay"
}
@@ -0,0 +1,402 @@
package com.hermesandroid.relay.network.shared
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.isValidHermesReach
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketAddress
import java.net.SocketException
import java.net.URI
import java.security.SecureRandom
import java.util.Base64
import java.util.ArrayDeque
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import javax.net.SocketFactory
private const val REACH_PROTOCOL_VERSION = 1
private const val REACH_MAX_FRAME_BYTES = 1024 * 1024
internal const val REACH_MAX_QUEUED_FRAMES = 32
internal const val REACH_MAX_QUEUED_BYTES = 8 * 1024 * 1024
private const val REACH_MATCH_TIMEOUT_MS = 10_000L
/**
* Connection metadata for Hermes Reach's outer WSS rendezvous.
*
* This is deliberately transport-only. The inner HTTPS/WSS origin and its
* pairing-authenticated SPKI pin continue to be owned by [PluginProxyRoutes],
* so broker reachability can never weaken Secure Link trust.
*/
data class HermesReachRoute(
val brokerUrl: String,
val hostId: String,
val credentialKind: String,
val token: String,
) {
fun tunnelUrlOrNull(): String? {
if (hostId.isBlank() || token.isBlank()) return null
if (credentialKind !in setOf("bootstrap", "route")) return null
val uri = runCatching { URI(brokerUrl.trim()) }.getOrNull() ?: return null
if (!uri.scheme.equals("wss", ignoreCase = true) || uri.host.isNullOrBlank()) return null
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return null
if (uri.rawPath.orEmpty().let { it.isNotEmpty() && it != "/" && it != "/v1/connect" }) return null
val authority = buildString {
append(if (':' in uri.host) "[${uri.host}]" else uri.host)
if (uri.port > 0 && uri.port != 443) append(":${uri.port}")
}
return "wss://$authority/v1/connect"
}
}
fun EndpointCandidate.hermesReachRouteOrNull(): HermesReachRoute? {
val metadata = broker?.takeIf { it.isValidHermesReach() } ?: return null
if (pluginProxyRoutesOrNull() == null) return null
return HermesReachRoute(
brokerUrl = metadata.url,
hostId = metadata.hostId,
credentialKind = metadata.credentialKind,
token = metadata.token,
)
}
/** Build the pinned inner Secure Link client over an outer Hermes Reach WSS. */
fun buildHermesReachClient(
baseBuilder: OkHttpClient.Builder,
outerClient: OkHttpClient,
candidate: EndpointCandidate,
sessionTokenProvider: () -> String?,
includeRelaySessionHeader: Boolean = true,
): OkHttpClient? {
val secureLink = candidate.pluginProxyRoutesOrNull() ?: return null
val reach = candidate.hermesReachRouteOrNull() ?: return null
return buildPluginProxyClient(
baseBuilder = baseBuilder,
routes = secureLink,
sessionTokenProvider = sessionTokenProvider,
includeRelaySessionHeader = includeRelaySessionHeader,
rawSocketFactory = HermesReachSocketFactory(outerClient, reach),
)
}
@Serializable
private data class ReachRegistration(
val type: String = "register",
@SerialName("protocol_version") val protocolVersion: Int = REACH_PROTOCOL_VERSION,
val role: String = "client",
@SerialName("host_id") val hostId: String,
@SerialName("connection_id") val connectionId: String,
@SerialName("credential_kind") val credentialKind: String,
val token: String,
)
@Serializable
private data class ReachControl(
val type: String? = null,
@SerialName("protocol_version") val protocolVersion: Int? = null,
@SerialName("stream_id") val streamId: String? = null,
val code: String? = null,
)
internal object HermesReachHandshake {
private val json = Json {
ignoreUnknownKeys = false
encodeDefaults = true
}
fun registration(route: HermesReachRoute, connectionId: String): String = json.encodeToString(
ReachRegistration(
hostId = route.hostId,
connectionId = connectionId,
credentialKind = route.credentialKind,
token = route.token,
),
)
fun validateMatched(payload: String): String? {
val control = runCatching { json.decodeFromString<ReachControl>(payload) }
.getOrElse { return "Hermes Reach returned an invalid match response" }
if (control.type == "error") {
return "Hermes Reach rejected the route (${control.code ?: "unknown"})"
}
val streamIdValid = control.streamId?.let(::isCanonicalId) == true
if (control.type != "matched" ||
control.protocolVersion != REACH_PROTOCOL_VERSION ||
!streamIdValid
) {
return "Hermes Reach returned a mismatched route response"
}
return null
}
private fun isCanonicalId(value: String): Boolean {
if (value.isBlank() || '=' in value) return false
val decoded = runCatching { Base64.getUrlDecoder().decode(value) }.getOrNull() ?: return false
return decoded.size == 16 && Base64.getUrlEncoder().withoutPadding().encodeToString(decoded) == value
}
}
/**
* Raw socket factory that carries bytes through Hermes Reach. OkHttp layers
* the normal Secure Link TLS socket factory over the returned socket, so SNI,
* hostname verification, and the QR SPKI pin all apply to the inner endpoint.
*/
class HermesReachSocketFactory(
private val outerClient: OkHttpClient,
private val route: HermesReachRoute,
) : SocketFactory() {
init {
require(route.tunnelUrlOrNull() != null) { "Invalid Hermes Reach route" }
}
override fun createSocket(): Socket = HermesReachSocket(outerClient, route)
override fun createSocket(host: String?, port: Int): Socket =
createSocket().apply { connect(InetSocketAddress(host, port)) }
override fun createSocket(host: String?, port: Int, localHost: InetAddress?, localPort: Int): Socket =
createSocket().apply {
if (localHost != null) bind(InetSocketAddress(localHost, localPort))
connect(InetSocketAddress(host, port))
}
override fun createSocket(host: InetAddress?, port: Int): Socket =
createSocket().apply { connect(InetSocketAddress(host, port)) }
override fun createSocket(
address: InetAddress?,
port: Int,
localAddress: InetAddress?,
localPort: Int,
): Socket = createSocket().apply {
if (localAddress != null) bind(InetSocketAddress(localAddress, localPort))
connect(InetSocketAddress(address, port))
}
}
private class HermesReachSocket(
private val outerClient: OkHttpClient,
private val route: HermesReachRoute,
) : Socket() {
private val inbound = ReachInputStream()
private val matchLatch = CountDownLatch(1)
private val connectionId = randomConnectionId()
@Volatile private var matchError: IOException? = null
@Volatile private var webSocket: WebSocket? = null
@Volatile private var connected = false
@Volatile private var closed = false
@Volatile private var matched = false
@Volatile private var remote: InetSocketAddress? = null
private var readTimeoutMs: Int = 0
private val outbound = object : OutputStream() {
override fun write(value: Int) = write(byteArrayOf(value.toByte()))
override fun write(bytes: ByteArray, offset: Int, length: Int) {
if (length == 0) return
if (!matched || closed) throw SocketException("Hermes Reach tunnel is not open")
var cursor = offset
var remaining = length
while (remaining > 0) {
val count = minOf(remaining, REACH_MAX_FRAME_BYTES)
val accepted = webSocket?.send(ByteString.of(*bytes.copyOfRange(cursor, cursor + count))) == true
if (!accepted) throw SocketException("Hermes Reach could not queue tunnel bytes")
cursor += count
remaining -= count
}
}
}
override fun connect(endpoint: SocketAddress?) = connect(endpoint, REACH_MATCH_TIMEOUT_MS.toInt())
override fun connect(endpoint: SocketAddress?, timeout: Int) {
if (connected) throw SocketException("Socket is already connected")
if (closed) throw SocketException("Socket is closed")
remote = endpoint as? InetSocketAddress
?: throw SocketException("Hermes Reach requires an internet socket target")
val request = Request.Builder().url(requireNotNull(route.tunnelUrlOrNull())).build()
webSocket = outerClient.newWebSocket(request, listener)
val waitMs = minOf(
timeout.takeIf { it > 0 }?.toLong() ?: REACH_MATCH_TIMEOUT_MS,
REACH_MATCH_TIMEOUT_MS,
)
if (!matchLatch.await(waitMs, TimeUnit.MILLISECONDS)) {
closeWithError(IOException("Hermes Reach host match timed out"))
}
matchError?.let { throw it }
if (!matched) throw IOException("Hermes Reach closed before matching the host")
connected = true
}
private val listener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
val registration = HermesReachHandshake.registration(route, connectionId)
if (!webSocket.send(registration)) {
closeWithError(IOException("Hermes Reach registration could not be sent"))
}
}
override fun onMessage(webSocket: WebSocket, text: String) {
if (matched) {
closeWithError(IOException("Hermes Reach sent text after matching"))
return
}
HermesReachHandshake.validateMatched(text)?.let { message ->
closeWithError(IOException(message))
return
}
matched = true
matchLatch.countDown()
}
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
if (!matched) {
closeWithError(IOException("Hermes Reach sent bytes before matching"))
return
}
if (bytes.size > REACH_MAX_FRAME_BYTES) {
closeWithError(IOException("Hermes Reach frame exceeds 1 MiB"))
return
}
if (!inbound.offer(bytes.toByteArray())) {
closeWithError(IOException("Hermes Reach receive queue exceeded its safe limit"))
}
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(code, null)
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
if (!matched) matchError = IOException("Hermes Reach closed before matching the host")
closed = true
inbound.close(matchError)
matchLatch.countDown()
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
closeWithError(IOException("Hermes Reach connection failed", t))
}
}
private fun closeWithError(error: IOException) {
matchError = error
closed = true
webSocket?.cancel()
inbound.close(error)
matchLatch.countDown()
}
override fun getInputStream(): InputStream {
if (!connected || closed) throw SocketException("Hermes Reach tunnel is not open")
inbound.readTimeoutMs = readTimeoutMs
return inbound
}
override fun getOutputStream(): OutputStream {
if (!connected || closed) throw SocketException("Hermes Reach tunnel is not open")
return outbound
}
override fun close() {
if (closed) return
closed = true
webSocket?.close(1000, null)
inbound.close(null)
matchLatch.countDown()
}
override fun isConnected(): Boolean = connected
override fun isClosed(): Boolean = closed
override fun getRemoteSocketAddress(): SocketAddress? = remote
override fun getInetAddress(): InetAddress? = remote?.address
override fun getPort(): Int = remote?.port ?: 0
override fun setSoTimeout(timeout: Int) { readTimeoutMs = timeout }
override fun getSoTimeout(): Int = readTimeoutMs
override fun setTcpNoDelay(on: Boolean) = Unit
override fun getTcpNoDelay(): Boolean = true
override fun setKeepAlive(on: Boolean) = Unit
override fun getKeepAlive(): Boolean = true
override fun setReuseAddress(on: Boolean) = Unit
override fun getReuseAddress(): Boolean = false
}
internal class ReachInputStream : InputStream() {
private val chunks = ArrayDeque<ByteArray>()
private var offset = 0
private var queuedBytes = 0
private var terminalError: IOException? = null
private var closed = false
@Volatile var readTimeoutMs: Int = 0
@Synchronized
fun offer(bytes: ByteArray): Boolean {
if (closed) return false
if (chunks.size >= REACH_MAX_QUEUED_FRAMES || queuedBytes + bytes.size > REACH_MAX_QUEUED_BYTES) {
return false
}
chunks.addLast(bytes)
queuedBytes += bytes.size
(this as java.lang.Object).notifyAll()
return true
}
@Synchronized
fun close(error: IOException?) {
if (closed) return
closed = true
terminalError = error
(this as java.lang.Object).notifyAll()
}
override fun read(): Int {
val one = ByteArray(1)
return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xff
}
@Synchronized
override fun read(target: ByteArray, targetOffset: Int, length: Int): Int {
if (length == 0) return 0
val started = System.nanoTime()
while (chunks.isEmpty() && !closed) {
val waitMs = if (readTimeoutMs > 0) {
val elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)
(readTimeoutMs - elapsed).coerceAtLeast(0)
} else 0L
if (readTimeoutMs > 0 && waitMs == 0L) throw java.net.SocketTimeoutException("Hermes Reach read timed out")
(this as java.lang.Object).wait(if (readTimeoutMs > 0) waitMs else 0L)
}
if (chunks.isEmpty()) {
terminalError?.let { throw it }
return -1
}
val chunk = chunks.first()
val count = minOf(length, chunk.size - offset)
chunk.copyInto(target, targetOffset, offset, offset + count)
offset += count
queuedBytes -= count
if (offset == chunk.size) {
chunks.remove(chunk)
offset = 0
}
return count
}
}
private fun randomConnectionId(): String {
val bytes = ByteArray(16).also(SecureRandom()::nextBytes)
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
}
@@ -0,0 +1,145 @@
package com.hermesandroid.relay.network.shared
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.ProxyEndpoint
import com.hermesandroid.relay.data.isValidPinnedProxy
import okhttp3.CertificatePinner
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import java.net.URI
import java.security.KeyStore
import java.security.MessageDigest
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
import javax.net.SocketFactory
/** Runtime endpoints exposed beneath one plugin-owned pinned-TLS origin. */
data class PluginProxyRoutes(
val authority: String,
val host: String,
val port: Int,
val relayHttpUrl: String,
val relayWebSocketUrl: String,
val apiBaseUrl: String?,
val dashboardBaseUrl: String?,
val pinSha256: String,
)
/**
* Resolve and validate the pairing-advertised proxy contract. Invalid or
* incomplete advertisements are never treated as secure routes.
*/
fun ProxyEndpoint.toPluginProxyRoutesOrNull(): PluginProxyRoutes? {
if (!isValidPinnedProxy()) return null
val base = url.trim().trimEnd('/')
val uri = runCatching { URI(base) }.getOrNull() ?: return null
if (!uri.scheme.equals("https", ignoreCase = true)) return null
val host = uri.host?.lowercase()?.takeIf { it.isNotBlank() } ?: return null
if (!uri.rawUserInfo.isNullOrBlank() || uri.rawQuery != null || uri.rawFragment != null) return null
val rawPath = uri.rawPath.orEmpty()
if (rawPath.isNotEmpty() && rawPath != "/") return null
val port = if (uri.port > 0) uri.port else 443
val pin = pinSha256!!.trim()
val authority = "$host:$port"
val wsBase = "wss://${formatHost(host)}${if (port == 443) "" else ":$port"}$rawPath"
.trimEnd('/')
val surfaces = surfaces.map(String::lowercase).toSet()
return PluginProxyRoutes(
authority = authority,
host = host,
port = port,
relayHttpUrl = "$base/relay",
relayWebSocketUrl = "$wsBase/relay/ws",
apiBaseUrl = "$base/api".takeIf { "api" in surfaces },
dashboardBaseUrl = "$base/dashboard".takeIf { "dashboard" in surfaces },
pinSha256 = pin,
)
}
fun EndpointCandidate.pluginProxyRoutesOrNull(): PluginProxyRoutes? =
proxy?.toPluginProxyRoutesOrNull()
private fun formatHost(host: String): String = if (':' in host) "[$host]" else host
/**
* Build a client that trusts the system normally, plus exactly the
* pairing-advertised SPKI for this proxy. The authority guard keeps a pin
* scoped to host *and port*; OkHttp's CertificatePinner alone is host-only.
*/
fun buildPluginProxyClient(
baseBuilder: OkHttpClient.Builder,
routes: PluginProxyRoutes,
sessionTokenProvider: () -> String?,
includeRelaySessionHeader: Boolean = true,
rawSocketFactory: SocketFactory? = null,
): OkHttpClient {
val expectedHost = routes.host
val expectedPort = routes.port
val systemTrust = systemTrustManager()
val pinnedTrust = PinnedOrSystemTrustManager(systemTrust, routes.pinSha256)
val sslContext = SSLContext.getInstance("TLS").apply {
init(null, arrayOf(pinnedTrust), SecureRandom())
}
if (rawSocketFactory != null) baseBuilder.socketFactory(rawSocketFactory)
return baseBuilder
.sslSocketFactory(sslContext.socketFactory, pinnedTrust)
.certificatePinner(
CertificatePinner.Builder().add(expectedHost, routes.pinSha256).build(),
)
.addNetworkInterceptor(Interceptor { chain ->
val requestUrl = chain.request().url
if (!requestUrl.host.equals(expectedHost, ignoreCase = true) ||
requestUrl.port != expectedPort
) {
throw java.io.IOException("Pinned proxy redirect left its paired authority")
}
val token = sessionTokenProvider().takeIf { includeRelaySessionHeader }
?.takeIf { it.isNotBlank() }
val request = if (token != null) {
chain.request().newBuilder()
.header("X-Hermes-Relay-Session", token)
.build()
} else {
chain.request()
}
chain.proceed(request)
})
.build()
}
private fun systemTrustManager(): X509TrustManager {
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
factory.init(null as KeyStore?)
return factory.trustManagers.filterIsInstance<X509TrustManager>().single()
}
private class PinnedOrSystemTrustManager(
private val system: X509TrustManager,
private val expectedPin: String,
) : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) =
system.checkClientTrusted(chain, authType)
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
val certificates = chain?.takeIf { it.isNotEmpty() }
?: throw CertificateException("Proxy supplied no certificate chain")
val systemAccepted = runCatching { system.checkServerTrusted(chain, authType) }.isSuccess
if (systemAccepted) return
val leaf = certificates.first()
leaf.checkValidity()
val actual = "sha256/" + java.util.Base64.getEncoder().encodeToString(
MessageDigest.getInstance("SHA-256").digest(leaf.publicKey.encoded),
)
if (!MessageDigest.isEqual(actual.toByteArray(), expectedPin.toByteArray())) {
throw CertificateException("Plugin proxy certificate does not match the paired pin")
}
}
override fun getAcceptedIssuers(): Array<X509Certificate> = system.acceptedIssuers
}
@@ -524,6 +524,29 @@ class ChatHandler {
}
}
/**
* Rebind visible user turns after Gateway rewrites a truncated durable
* prefix. The response is positional in the same user-ordinal space used
* for edit/regenerate. Missing entries clear cached ids so a later rewind
* cannot accidentally send an archived pre-rewrite row id.
*/
fun rebindSurvivorUserRowIds(rowIds: List<Long?>) {
var ordinal = 0
_messages.update { messages ->
messages.map { message ->
if (!message.isGatewayRewindUser()) return@map message
val rebound = rowIds.getOrNull(ordinal)
ordinal += 1
if (message.rowId == rebound) message else message.copy(rowId = rebound)
}
}
}
private fun ChatMessage.isGatewayRewindUser(): Boolean =
role == MessageRole.USER &&
!id.startsWith("voice-intent-") &&
!id.startsWith("steer-")
fun replaceMessageContent(messageId: String, content: String) {
_messages.update { messages ->
messages.map { message ->
@@ -1497,6 +1520,7 @@ class ChatHandler {
// this as the same visible row across the post-turn reload.
prior.copy(
id = messageId,
rowId = item.rowId,
role = role,
content = cleanedContent,
attachments = carriedAttachments,
@@ -1527,6 +1551,7 @@ class ChatHandler {
// nothing local to carry).
ChatMessage(
id = messageId,
rowId = item.rowId,
role = role,
content = cleanedContent,
attachments = carriedAttachments,
@@ -2036,6 +2061,13 @@ class ChatHandler {
hasModelConfig = item.hasModelConfig,
pinned = item.pinned,
archived = item.archived,
workingDirectory = item.cwd,
gitBranch = item.gitBranch,
gitRepoRoot = item.gitRepoRoot,
pullRequestNumber = item.pullRequest?.number,
pullRequestUrl = item.pullRequest?.url,
pullRequestState = item.pullRequest?.state,
pullRequestDraft = item.pullRequest?.draft == true,
)
}.sortedByDescending { it.activityTimestamp }
// Preserve the active session's optimistic row when the server list
@@ -7,9 +7,12 @@ import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.network.upstream.models.MessageListResponse
import com.hermesandroid.relay.network.upstream.models.SessionItem
import com.hermesandroid.relay.network.upstream.models.SessionListResponse
import com.hermesandroid.relay.network.upstream.models.SessionPullRequest
import com.hermesandroid.relay.network.upstream.models.SessionPullRequestScanResponse
import com.hermesandroid.relay.network.upstream.models.SessionPruneFilters
import com.hermesandroid.relay.network.upstream.models.SessionPrunePreview
import com.hermesandroid.relay.network.upstream.models.SessionPruneResult
import com.hermesandroid.relay.network.upstream.models.RepositoryPullRequestListResponse
import com.hermesandroid.relay.auth.SecureStoreCache
import com.hermesandroid.relay.auth.SessionTokenStore
import com.hermesandroid.relay.auth.buildRawTokenStore
@@ -35,13 +38,18 @@ import okhttp3.CookieJar
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.URLEncoder
import java.util.concurrent.TimeUnit
import okio.BufferedSink
// Status/session/provider snapshots are @Serializable so the Manage tab's
// disk cache (DashboardManageDiskCache) can persist Loaded entries verbatim.
@@ -67,6 +75,23 @@ data class DashboardGatewayTopology(
@SerialName("served_profiles") val servedProfiles: List<String> = emptyList(),
)
/**
* Return only profiles the launch gateway positively reports as served.
*
* `/api/status.profiles` is the installed-profile inventory. Selective
* multiplex serving can exclude an installed profile, so that list must never
* authorize construction of a `/p/<profile>` API fallback route.
*/
internal fun DashboardStatus.multiplexServedProfiles(): List<String> {
if (!gatewayMode.equals("multiplex", ignoreCase = true)) return emptyList()
return gateways.firstOrNull { it.profile.equals("default", ignoreCase = true) }
?.servedProfiles
.orEmpty()
.map(String::trim)
.filter(String::isNotBlank)
.distinct()
}
@Serializable
data class DashboardComponentHealthRollup(
val supported: Boolean = false,
@@ -173,6 +198,71 @@ data class DashboardCustomEndpointValidation(
val models: List<String>,
)
internal class BoundedStreamRequestBody(
private val declaredLength: Long?,
private val limitBytes: Long,
private val openStream: () -> InputStream,
) : RequestBody() {
init {
require(limitBytes > 0)
require(declaredLength == null || declaredLength >= 0)
require(declaredLength == null || declaredLength <= limitBytes) {
"Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB upload limit."
}
}
override fun contentType() = "application/zip".toMediaType()
override fun contentLength(): Long = declaredLength ?: -1L
override fun writeTo(sink: BufferedSink) {
openStream().use { input ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var written = 0L
while (true) {
val read = input.read(buffer)
if (read < 0) break
written += read
if (written > limitBytes) {
throw IOException("Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB upload limit.")
}
sink.write(buffer, 0, read)
}
if (declaredLength != null && written != declaredLength) {
throw IOException("Backup archive changed while it was being read.")
}
}
}
}
internal fun copyBounded(
input: InputStream,
output: OutputStream,
declaredLength: Long?,
limitBytes: Long,
): Long {
require(limitBytes > 0)
require(declaredLength == null || declaredLength >= 0)
require(declaredLength == null || declaredLength <= limitBytes) {
"Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB download limit."
}
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var written = 0L
while (true) {
val read = input.read(buffer)
if (read < 0) break
written += read
if (written > limitBytes) {
throw IOException("Backup archive exceeds the ${limitBytes / (1024 * 1024)} MB download limit.")
}
output.write(buffer, 0, read)
}
if (declaredLength != null && written != declaredLength) {
throw IOException("Backup archive changed while it was being downloaded.")
}
return written
}
/** One entry from `GET /api/audio/elevenlabs/voices` — non-secret voice metadata. */
data class ElevenLabsVoice(
val voiceId: String,
@@ -206,8 +296,14 @@ class DashboardApiClient(
isLenient = true
coerceInputValues = true
},
private val nowMillis: () -> Long = System::currentTimeMillis,
) {
private val baseUrl: String = baseUrl.trim().trimEnd('/')
private val sessionPrScanLock = Any()
private val sessionPrScannedAt = mutableMapOf<String, Long>()
private val sessionPrScanWasTerminal = mutableMapOf<String, Boolean>()
private val sessionPullRequests = mutableMapOf<String, SessionPullRequest>()
private var sessionPrScanSupported: Boolean? = null
/**
* Resolve a request URL without ever throwing. okhttp's
@@ -518,6 +614,157 @@ class DashboardApiClient(
suspend fun createServerBackup(): Result<JsonObject> =
postJsonObject("/api/ops/backup")
/** Download only archives created inside upstream's guarded dashboard backup directory. */
suspend fun downloadServerBackup(
archive: String,
openOutput: () -> OutputStream,
): Result<String> = download(
path = "/api/ops/backup/download?archive=${queryValue(archive)}",
operation = "Hermes backup",
openOutput = openOutput,
)
/** Import a server-local archive path after the user confirms the destructive restore. */
suspend fun importServerBackup(archive: String): Result<JsonObject> =
postJsonObject(
path = "/api/ops/import",
payload = buildJsonObject { put("archive", archive) },
)
/** Upload an Android-selected zip to upstream's guarded staging directory and start import. */
suspend fun uploadServerBackup(
filename: String,
contentLength: Long?,
openStream: () -> InputStream,
force: Boolean = false,
): Result<JsonObject> = withContext(Dispatchers.IO) {
val path = "/api/ops/import-upload"
val httpUrl = resolveUrl(path) ?: return@withContext Result.failure(invalidUrlException())
val body = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("force", force.toString())
.addFormDataPart(
"file",
filename.ifBlank { "hermes-backup.zip" },
runCatching {
BoundedStreamRequestBody(contentLength, MAX_BACKUP_TRANSFER_BYTES, openStream)
}.getOrElse { return@withContext Result.failure(it) },
)
.build()
executeJson(Request.Builder().url(httpUrl).post(body).build(), path)
}
suspend fun getLearningNode(id: String, profile: String? = null): Result<JsonObject> =
getJsonObject("/api/learning/node?id=${queryValue(id)}${profileQuerySuffix(profile)}")
suspend fun updateLearningNode(
id: String,
content: String,
profile: String? = null,
): Result<JsonObject> = putJsonObject(
path = "/api/learning/node",
payload = buildJsonObject {
put("id", id)
put("content", content)
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
},
)
suspend fun deleteLearningNode(id: String, profile: String? = null): Result<JsonObject> =
deleteJsonObjectWithBody(
path = "/api/learning/node",
payload = buildJsonObject {
put("id", id)
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
},
)
suspend fun selectMemoryProvider(provider: String): Result<JsonObject> =
putJsonObject(
path = "/api/memory/provider",
payload = buildJsonObject { put("provider", provider) },
)
/** Activate an already-configured provider inside the selected upstream profile. */
suspend fun activateMemoryProvider(provider: String, profile: String? = null): Result<JsonObject> =
updateMemoryProviderConfig(provider, JsonObject(emptyMap()), profile)
suspend fun getMemoryProviderConfig(
provider: String,
profile: String? = null,
): Result<JsonObject> = getJsonObject(
"/api/memory/providers/${pathSegment(provider)}/config${profileQuery(profile)}",
)
suspend fun updateMemoryProviderConfig(
provider: String,
values: JsonObject,
profile: String? = null,
): Result<JsonObject> = putJsonObject(
path = "/api/memory/providers/${pathSegment(provider)}/config${profileQuery(profile)}",
payload = buildJsonObject { put("values", values) },
)
suspend fun setupMemoryProvider(provider: String): Result<JsonObject> =
postJsonObject(
path = "/api/memory/providers/${pathSegment(provider)}/setup",
// Dependency installation is host-global upstream. Do not submit
// profile-owned values through this unscoped route.
payload = buildJsonObject { put("values", JsonObject(emptyMap())) },
)
suspend fun startWhatsAppOnboarding(
mode: String,
allowedUsers: String,
profile: String? = null,
): Result<JsonObject> = postJsonObject(
path = "/api/messaging/whatsapp/onboarding/start",
payload = buildJsonObject {
put("mode", mode)
put("allowed_users", allowedUsers)
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
},
)
suspend fun getWhatsAppOnboarding(pairingId: String): Result<JsonObject> =
getJsonObject("/api/messaging/whatsapp/onboarding/${pathSegment(pairingId)}")
suspend fun applyWhatsAppOnboarding(
pairingId: String,
mode: String,
allowedUsers: String,
profile: String? = null,
): Result<JsonObject> = postJsonObject(
path = "/api/messaging/whatsapp/onboarding/${pathSegment(pairingId)}/apply",
payload = buildJsonObject {
put("mode", mode)
put("allowed_users", allowedUsers)
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
},
)
suspend fun cancelWhatsAppOnboarding(pairingId: String): Result<JsonObject> =
deleteJsonObject("/api/messaging/whatsapp/onboarding/${pathSegment(pairingId)}")
suspend fun setMessagingPlatformEnabled(
platform: String,
enabled: Boolean,
profile: String? = null,
): Result<JsonObject> = putJsonObject(
path = "/api/messaging/platforms/${pathSegment(platform)}${profileQuery(profile)}",
payload = buildJsonObject {
put("enabled", enabled)
put("env", JsonObject(emptyMap()))
put("clear_env", JsonArray(emptyList()))
profile?.trim()?.takeIf(String::isNotBlank)?.let { put("profile", it) }
},
)
suspend fun testMessagingPlatform(platform: String, profile: String? = null): Result<JsonObject> =
postJsonObject(
"/api/messaging/platforms/${pathSegment(platform)}/test${profileQuery(profile)}",
)
suspend fun setProfileDescription(name: String, description: String): Result<JsonObject> =
putJsonObject(
path = "/api/profiles/${pathSegment(name)}/description",
@@ -764,7 +1011,13 @@ class DashboardApiClient(
pageSessions.forEach { sessions.putIfAbsent(it.id, it) }
if (pageSessions.size < page.limit) break
}
Result.success(sessions.values.take(limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)))
Result.success(
enrichSessionWorkState(
sessions.values.take(limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)),
fixedProfile = profile?.trim()?.takeIf { it.isNotBlank() }
?: DEFAULT_SESSION_PROFILE_SCOPE,
),
)
}
/**
@@ -776,7 +1029,7 @@ class DashboardApiClient(
limit: Int = SESSION_LIST_WINDOW_LIMIT,
): Result<List<SessionItem>> = withContext(Dispatchers.IO) {
val boundedLimit = limit.coerceIn(1, SESSION_LIST_WINDOW_LIMIT)
getJson(
val result = getJson(
"/api/profiles/sessions?limit=$boundedLimit&offset=0&order=recent" +
"&min_messages=1&archived=include&profile=all",
).mapCatching { root ->
@@ -786,8 +1039,129 @@ class DashboardApiClient(
.distinctBy { "${it.profile}:${it.id}" }
.take(boundedLimit)
}
if (result.isFailure) return@withContext result
Result.success(enrichSessionWorkState(result.getOrThrow(), fixedProfile = null))
}
/**
* Attach the PR a coding session created using the current upstream
* transcript-backed endpoint. Repository and branch already arrive on the
* list row. Missing/older endpoints are deliberately ignored, leaving the
* original rows intact. Active misses retry on a bounded cadence; terminal
* rows get one final scan and resolved associations remain cached.
*/
private suspend fun enrichSessionWorkState(
sessions: List<SessionItem>,
fixedProfile: String?,
): List<SessionItem> {
val candidates = sessions.filter {
it.id.isNotBlank() &&
(!it.gitRepoRoot.isNullOrBlank() || !it.gitBranch.isNullOrBlank() || !it.cwd.isNullOrBlank())
}
val duplicateIds = if (fixedProfile == null) {
candidates.groupingBy { it.id }.eachCount().filterValues { it > 1 }.keys
} else {
emptySet()
}
val now = nowMillis()
val pending = synchronized(sessionPrScanLock) {
candidates.filter { session ->
if (session.id in duplicateIds) return@filter false
val key = sessionWorkKey(session, fixedProfile)
val scannedAt = sessionPrScannedAt[key]
val resolved = sessionPullRequests[key] != null
!resolved && when {
scannedAt == null -> true
session.endedAt != null -> sessionPrScanWasTerminal[key] != true
else -> now - scannedAt >= ACTIVE_SESSION_PR_MISS_TTL_MILLIS
}
}
}
val pendingIds = pending.map { it.id }.distinct()
if (pendingIds.isNotEmpty()) {
val payload = buildJsonObject {
put("ids", JsonArray(pendingIds.map { JsonPrimitive(it) }))
}
val scan = postJsonObject("/api/profiles/sessions/pull-requests", payload)
.mapCatching { root ->
json.decodeFromJsonElement(SessionPullRequestScanResponse.serializer(), root)
}
synchronized(sessionPrScanLock) {
// A legacy 404 is a compatibility outcome, not a session-list failure.
// Avoid hammering an unsupported host on every drawer refresh.
if (scan.isSuccess || sessionPrScanSupported == null) {
sessionPrScanSupported = scan.isSuccess
}
pending.forEach { session ->
val key = sessionWorkKey(session, fixedProfile)
sessionPrScannedAt[key] = now
sessionPrScanWasTerminal[key] = session.endedAt != null
scan.getOrNull()?.pullRequests?.get(session.id)?.takeIf {
it.number > 0 && it.url.isNotBlank()
}?.let { pullRequest ->
sessionPullRequests[key] = pullRequest
}
}
}
}
refreshPullRequestStates(candidates, fixedProfile)
val pullRequests = synchronized(sessionPrScanLock) { sessionPullRequests.toMap() }
return sessions.map { session ->
session.copy(pullRequest = pullRequests[sessionWorkKey(session, fixedProfile)])
}
}
/** Refresh current PR lifecycle state using upstream's repo-scoped GitHub view. */
private suspend fun refreshPullRequestStates(
sessions: List<SessionItem>,
fixedProfile: String?,
) {
if (synchronized(sessionPrScanLock) { sessionPrScanSupported } != true) return
val known = synchronized(sessionPrScanLock) { sessionPullRequests.toMap() }
sessions.groupBy { (it.gitRepoRoot ?: it.cwd).orEmpty().trim() }
.filterKeys { it.isNotBlank() }
.forEach { (path, repositorySessions) ->
val branches = repositorySessions.mapNotNull { it.gitBranch?.trim() }
.filter { it.isNotBlank() }
.distinct()
val numbers = repositorySessions.mapNotNull {
known[sessionWorkKey(it, fixedProfile)]?.number
}
.filter { it > 0 }
.distinct()
if (branches.isEmpty() && numbers.isEmpty()) return@forEach
val payload = buildJsonObject {
put("path", path)
put("branches", JsonArray(branches.map { JsonPrimitive(it) }))
put("numbers", JsonArray(numbers.map { JsonPrimitive(it) }))
}
val response = postJsonObject("/api/git/review/pr-list", payload)
.mapCatching { root ->
json.decodeFromJsonElement(RepositoryPullRequestListResponse.serializer(), root)
}
.getOrNull()
?: return@forEach
if (!response.ghReady) return@forEach
synchronized(sessionPrScanLock) {
repositorySessions.forEach { session ->
val key = sessionWorkKey(session, fixedProfile)
val recovered = sessionPullRequests[key]
val current = response.prs.firstOrNull { pr ->
recovered != null && pr.number == recovered.number
} ?: response.prs.firstOrNull { pr ->
!session.gitBranch.isNullOrBlank() && pr.branch == session.gitBranch
}
if (current != null && current.number > 0 && current.url.isNotBlank()) {
sessionPullRequests[key] = current
}
}
}
}
}
private fun sessionWorkKey(session: SessionItem, fixedProfile: String?): String =
"${fixedProfile ?: session.profile.orEmpty()}\u0000${session.id}"
/**
* A session's message history, scoped to its owning profile via the dashboard
* `GET /api/sessions/{id}/messages?profile=`. Required twin of [listSessions]:
@@ -1110,8 +1484,44 @@ class DashboardApiClient(
}
}
private suspend fun download(
path: String,
operation: String,
openOutput: () -> OutputStream,
): Result<String> =
withContext(Dispatchers.IO) {
val httpUrl = resolveUrl(path) ?: return@withContext Result.failure(invalidUrlException())
val request = Request.Builder().url(httpUrl).get().build()
try {
okHttpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) return@withContext Result.failure(apiFailure(response, operation))
val disposition = response.header("Content-Disposition").orEmpty()
val filename = Regex("filename=\\\"?([^\\\";]+)").find(disposition)?.groupValues?.get(1)
?: "hermes-backup.zip"
val body = response.body
val declaredLength = body.contentLength().takeIf { it >= 0 }
if (declaredLength != null && declaredLength > MAX_BACKUP_TRANSFER_BYTES) {
throw IOException("Backup archive exceeds the ${MAX_BACKUP_TRANSFER_BYTES / (1024 * 1024)} MB download limit.")
}
openOutput().use { output ->
body.byteStream().use { input ->
copyBounded(input, output, declaredLength, MAX_BACKUP_TRANSFER_BYTES)
}
}
Result.success(filename)
}
} catch (e: Exception) {
Result.failure(e)
}
}
companion object {
private val JSON_MEDIA = "application/json; charset=utf-8".toMediaType()
private const val DEFAULT_SESSION_PROFILE_SCOPE = "__dashboard_default__"
internal const val ACTIVE_SESSION_PR_MISS_TTL_MILLIS = 60_000L
// Mirrors current upstream `_MANAGED_FILE_MAX_BYTES`; enforcing it
// client-side avoids uploading a body the Dashboard will reject.
internal const val MAX_BACKUP_TRANSFER_BYTES = 100L * 1024L * 1024L
fun pathSegment(value: String): String =
URLEncoder.encode(value, "UTF-8").replace("+", "%20")
@@ -1169,6 +1579,11 @@ class DashboardApiClient(
return if (trimmed.isBlank()) "" else "?profile=${pathSegment(trimmed)}"
}
private fun profileQuerySuffix(profile: String?): String {
val trimmed = profile?.trim().orEmpty()
return if (trimmed.isBlank()) "" else "&profile=${queryValue(trimmed)}"
}
private fun profileLimitQuery(profile: String?, limit: Int): String {
val params = buildList {
val trimmed = profile?.trim().orEmpty()
@@ -1,6 +1,14 @@
package com.hermesandroid.relay.network.upstream
import android.util.Log
import com.hermesandroid.relay.data.GatewayProfileConfigureResult
import com.hermesandroid.relay.data.GatewayProfileDescription
import com.hermesandroid.relay.data.GatewayProfileEditorClient
import com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException
import com.hermesandroid.relay.data.GatewayProfilePatch
import com.hermesandroid.relay.data.GatewayProfileSection
import com.hermesandroid.relay.data.GatewayProfileSkill
import com.hermesandroid.relay.data.GatewayProfileToolset
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.network.upstream.models.UsageInfo
import com.hermesandroid.relay.util.AppForegroundTracker
@@ -90,9 +98,11 @@ class GatewayChatClient(
private val turnIdleTimeoutMs: Long = TURN_TIMEOUT_MS,
/** Random source for ordinary reconnect full-jitter. */
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
) {
) : GatewayProfileEditorClient {
/** Existing upstream rich-chat vocabulary; do not invent a Relay-only source. */
private val sessionSource = "webui"
@Volatile
private var profileEditorSupported: Boolean? = null
companion object {
private const val TAG = "GatewayChatClient"
@@ -513,6 +523,10 @@ class GatewayChatClient(
* into the session's USER messages (counted from the first user
* message). The server drops that message and everything after it
* before running [text] as a fresh turn.
* @param truncateBeforeRowId durable identity of the same target user row
* when current Gateway history supplied one. Sent alongside the ordinal
* so the server can fail closed if local position and durable identity
* diverge; omitted for older Gateway history without row ids.
* @param queuedFollowUp true only when Android is draining a prompt the
* user explicitly queued behind an active turn. Newer gateways use the
* additive `queued:true` marker to preserve run-after semantics while
@@ -530,7 +544,9 @@ class GatewayChatClient(
callbacks: GatewayTurnCallbacks,
attachments: List<GatewayAttachment> = emptyList(),
truncateBeforeUserOrdinal: Int? = null,
truncateBeforeRowId: Long? = null,
queuedFollowUp: Boolean = false,
onSurvivorUserRowIds: (List<Long?>) -> Unit = { },
onPreflightFailure: (reason: String) -> Unit,
): ActiveTurnHandle {
val turn = GatewayTurn(dispatchOn(callbacks))
@@ -552,25 +568,42 @@ class GatewayChatClient(
turn.tracer.mark("session")
}
if (turn.cancelled) return@launch
attachments.forEach { attachment ->
uploadAttachment(attachment).getOrElse { e ->
val attachmentRefs = attachments.mapNotNull { attachment ->
val upload = uploadAttachment(attachment).getOrElse { e ->
throw GatewayPreflightException("attachment upload failed: ${e.message}")
}
if (attachment.requiresPromptReference()) {
upload.stringField("ref_text")
?: throw GatewayPreflightException(
"attachment upload failed: Hermes returned no readable file reference",
)
} else {
null
}
}
if (turn.cancelled) return@launch
if (!awaitCancelledTurnDrain(turn, storedSessionId)) return@launch
activeTurn = turn
turn.armWatchdog()
// Generic `file.attach` uploads are staged artifacts, not
// session-owned image/PDF attachments. The gateway returns
// the exact workspace/sandbox-safe `@file:` reference that
// must accompany this prompt. Keep the user's prose last,
// matching upstream Desktop's context-reference contract.
val submittedText = (attachmentRefs + text)
.filter(String::isNotBlank)
.joinToString("\n\n")
val submitted = rpc(
"prompt.submit",
buildJsonObject {
put("session_id", liveSessionId ?: error("no live session"))
put("text", text)
put("text", submittedText)
truncateBeforeUserOrdinal?.let { ordinal ->
put("truncate_before_user_ordinal", ordinal)
put("confirm_truncate", true)
if (ordinal == 0) put("confirm_empty_truncate", true)
}
truncateBeforeRowId?.let { put("truncate_before_row_id", it) }
if (queuedFollowUp) put("queued", true)
},
// Long-running RPC, not a generic 15s ack — see the
@@ -613,12 +646,25 @@ class GatewayChatClient(
submitError?.message ?: "prompt.submit failed",
)
}
(submitted.getOrNull()?.get("survivor_user_row_ids") as? JsonArray)?.let { raw ->
val rebound = raw.map { element ->
(element as? JsonPrimitive)?.longOrNull
}
callbackDispatcher { onSurvivorUserRowIds(rebound) }
}
turn.tracer.mark("submit")
// One INFO line per turn so logcat shows which transport
// served a send — the SSE paths log their SSE events, and
// a silent happy path here made on-device verification a
// read-the-absence exercise.
Log.i(TAG, "Gateway turn submitted (session=$storedSessionId)")
} catch (e: GatewayAuthoritativeResumeException) {
if (activeTurn === turn) activeTurn = null
if (!turn.cancelled) {
turn.disarmWatchdog()
turn.tracer.done("resume-rejected")
turn.callbacks.onError(e.message ?: "Hermes could not resume this session")
}
} catch (e: Exception) {
if (activeTurn === turn) activeTurn = null
if (!turn.cancelled) {
@@ -1107,8 +1153,14 @@ class GatewayChatClient(
private fun JsonObject.toGatewayCompressResult(): GatewayCompressResult =
GatewayCompressResult(
status = stringField("status") ?: "completed",
output = stringField("output"),
status = stringField("status") ?: if (
(this["compressed"] as? JsonPrimitive)?.booleanOrNull == false
) {
"noop"
} else {
"completed"
},
output = stringField("output") ?: stringField("message"),
removed = (this["removed"] as? JsonPrimitive)?.intOrNull,
beforeMessages = (this["before_messages"] as? JsonPrimitive)?.intOrNull,
afterMessages = (this["after_messages"] as? JsonPrimitive)?.intOrNull,
@@ -1228,6 +1280,120 @@ class GatewayChatClient(
.onSuccess { commandsCatalogCache = it }
}
/**
* Capability probe and authoritative editor snapshot. A method-not-found
* response is sticky for this client so older Hermes builds keep using the
* existing Relay inspector without repeatedly sending unsupported RPCs.
*/
override suspend fun describeProfile(
profileName: String,
): Result<GatewayProfileDescription> {
if (profileEditorSupported == false) {
return Result.failure(GatewayProfileEditorUnsupportedException())
}
val name = profileName.trim()
if (name.isEmpty()) return Result.failure(IllegalArgumentException("profile name required"))
try {
connectMutex.withLock { ensureConnected() }
} catch (e: Exception) {
return Result.failure(e)
}
val response = rpc(
"profiles.describe",
buildJsonObject { put("name", name) },
)
val error = response.exceptionOrNull()
if (error.isMethodNotFound()) {
profileEditorSupported = false
return Result.failure(GatewayProfileEditorUnsupportedException())
}
return response.mapCatching { payload ->
parseProfileDescription(payload, expectedName = name)
}.onSuccess {
profileEditorSupported = true
}
}
/** Apply only fields explicitly present in [patch]; requires a successful describe first. */
override suspend fun configureProfile(
profileName: String,
patch: GatewayProfilePatch,
): Result<GatewayProfileConfigureResult> {
if (profileEditorSupported != true) {
return Result.failure(GatewayProfileEditorUnsupportedException())
}
val name = profileName.trim()
if (name.isEmpty()) return Result.failure(IllegalArgumentException("profile name required"))
if ((patch.provider == null) != (patch.model == null)) {
return Result.failure(IllegalArgumentException("provider and model must be saved together"))
}
val requested = patch.requestedSections
if (requested.isEmpty()) return Result.success(GatewayProfileConfigureResult(emptySet(), emptySet()))
val params = buildJsonObject {
put("name", name)
patch.description?.let { put("description", it) }
patch.soul?.let { put("soul", it) }
patch.provider?.let { put("provider", it) }
patch.model?.let { put("model", it) }
patch.disabledSkills?.let { names ->
put("disabled_skills", JsonArray(names.map(::JsonPrimitive)))
}
patch.enabledToolsets?.let { names ->
put("enabled_toolsets", JsonArray(names.map(::JsonPrimitive)))
}
}
return rpc("profiles.configure", params).mapCatching { payload ->
val appliedObject = payload["applied"] as? JsonObject
?: throw GatewayRpcException("profiles.configure returned no applied map")
val applied = requested.filterTo(linkedSetOf()) { section ->
(appliedObject[section.wireName] as? JsonPrimitive)?.booleanOrNull == true
}
GatewayProfileConfigureResult(requested = requested, applied = applied)
}
}
private fun parseProfileDescription(
payload: JsonObject,
expectedName: String,
): GatewayProfileDescription {
val name = payload.stringField("name")
?: throw GatewayRpcException("profiles.describe returned no profile name")
if (name != expectedName) {
throw GatewayRpcException("profiles.describe returned a different profile")
}
val model = payload["model"] as? JsonObject ?: JsonObject(emptyMap())
val skills = (payload["skills"] as? JsonArray).orEmpty().mapNotNull { item ->
val obj = item as? JsonObject ?: return@mapNotNull null
val skillName = obj.stringField("name")?.takeIf(String::isNotBlank)
?: return@mapNotNull null
GatewayProfileSkill(
name = skillName,
enabled = (obj["enabled"] as? JsonPrimitive)?.booleanOrNull ?: true,
)
}
val toolsets = (payload["toolsets"] as? JsonArray).orEmpty().mapNotNull { item ->
val obj = item as? JsonObject ?: return@mapNotNull null
val toolsetName = obj.stringField("name")?.takeIf(String::isNotBlank)
?: return@mapNotNull null
GatewayProfileToolset(
name = toolsetName,
description = obj.stringField("description").orEmpty(),
toolCount = (obj["tool_count"] as? JsonPrimitive)?.intOrNull ?: 0,
enabled = (obj["enabled"] as? JsonPrimitive)?.booleanOrNull ?: true,
)
}
return GatewayProfileDescription(
name = name,
description = payload.stringField("description").orEmpty(),
soul = payload.stringField("soul").orEmpty(),
provider = model.stringField("provider").orEmpty(),
model = model.stringField("default").orEmpty(),
skills = skills,
toolsets = toolsets,
toolsetsPinned = (payload["toolsets_pinned"] as? JsonPrimitive)?.booleanOrNull ?: false,
)
}
/**
* Fetch the upstream gateway's cropped preview for a Petdex pet.
*
@@ -1993,6 +2159,12 @@ class GatewayChatClient(
},
)
val result = resumed.getOrNull()
val resumeError = resumed.exceptionOrNull()
if ((resumeError as? GatewayRpcException)?.code == 4130) {
throw GatewayAuthoritativeResumeException(
resumeError.message ?: "Session transcript exceeds the configured resume limit",
)
}
val live = result?.stringField("session_id")
if (live != null) {
liveSessionId = live
@@ -2683,6 +2855,11 @@ class GatewayChatClient(
}
}
private fun GatewayAttachment.requiresPromptReference(): Boolean {
val mime = contentType.substringBefore(';').trim().lowercase()
return !mime.startsWith("image/") && mime != "application/pdf"
}
/**
* Upload one image. Tries the upstream RPC name first; on method-not-found
* falls back ONCE per socket to the legacy dotted name (older builds
@@ -3161,14 +3338,21 @@ internal class GatewayPreflightException(message: String) : Exception(message)
/** One connect attempt failed; [GatewayChatClient] may retry with a fresh ticket. */
internal class GatewayConnectAttemptException(message: String) : Exception(message)
/** Server intentionally refused a durable resume; never create/fallback into a context-free turn. */
internal class GatewayAuthoritativeResumeException(message: String) : Exception(message)
/** [code] is the JSON-RPC error code when the failure came from the server (e.g. 4018, -32601). */
internal class GatewayRpcException(message: String, val code: Int? = null) : Exception(message)
private const val JSONRPC_METHOD_NOT_FOUND = -32601
private val AUTHORITATIVE_PROMPT_SUBMIT_REJECTIONS = setOf(
4004, // malformed truncation target
4018, // durable/ordinal target is no longer present
4028, // first-turn truncate requires explicit empty-history confirmation
4029, // every destructive truncate requires explicit confirmation
4030, // durable row id and client ordinal disagree
4090, // active-session capacity policy
5008, // durable truncation could not be persisted
5070, // initial session persistence failed: storage full
5071, // other authoritative initial session persistence failure
)
@@ -444,15 +444,26 @@ class GatewayEventMapper(
}
fun interactionRequest(type: String, payload: JsonObject?): GatewayAsk? = when (type) {
"clarify.request" -> GatewayAsk(
kind = GatewayAsk.Kind.CLARIFY,
requestId = payload.string("request_id"),
text = payload.string("question") ?: "The agent needs clarification",
choices = (payload?.get("choices") as? JsonArray)
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
?.takeIf { it.isNotEmpty() },
timeoutSeconds = CLARIFY_TIMEOUT_SECONDS,
)
"clarify.request" -> {
val choices = (payload?.get("choices") as? JsonArray)
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim() }
?.filter { it.isNotEmpty() }
?.distinct()
?.take(MAX_CLARIFY_CHOICES)
?.takeIf { it.isNotEmpty() }
GatewayAsk(
kind = GatewayAsk.Kind.CLARIFY,
requestId = payload.string("request_id"),
text = payload.string("question") ?: "The agent needs clarification",
choices = choices,
multiSelect = payload.boolean("multi_select") == true && choices != null,
// Current upstream owns expiry through clarify.expire and
// does not advertise its configurable deadline. Never
// invent a local deadline; consume future additive
// metadata only when it is present and positive.
timeoutSeconds = payload.int("timeout_seconds")?.coerceAtLeast(0) ?: 0,
)
}
"approval.request" -> GatewayAsk(
kind = GatewayAsk.Kind.APPROVAL,
@@ -561,9 +572,9 @@ class GatewayEventMapper(
}
}
// Upstream `_block()` timeouts per ask kind (server.py) — the blocked thread
// resolves to "" when these elapse. Approval has none (session-scoped).
private const val CLARIFY_TIMEOUT_SECONDS = 300
// Upstream clarify tool accepts at most four choices. Sudo/secret retain fixed
// `_block()` timeouts; clarify is configurable and expires authoritatively.
private const val MAX_CLARIFY_CHOICES = 4
private const val SUDO_TIMEOUT_SECONDS = 120
private const val SECRET_TIMEOUT_SECONDS = 300
@@ -583,6 +594,12 @@ private fun JsonObject?.approvalChoices(): List<String>? =
(this?.get("choices") as? JsonArray)
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.lowercase() }
?.filter { it in setOf("once", "session", "always", "deny") }
// Scope-denial flags are authoritative. Current upstream protected-
// instruction requests set both flags false, but gateway event builders
// can still include the broader session choice in `choices`.
// Never offer a scope the request explicitly forbids.
?.filterNot { it == "session" && this.boolean("allow_session") == false }
?.filterNot { it == "always" && this.boolean("allow_permanent") == false }
?.distinct()
?.takeIf { it.isNotEmpty() }
@@ -218,13 +218,15 @@ data class GatewayAsk(
val text: String,
/** Server-advertised answers for clarify and approval requests. */
val choices: List<String>? = null,
/** Clarify-only: several advertised choices may be returned together. */
val multiSelect: Boolean = false,
/** Approval-only: the smart observer denied and the owner may override once. */
val smartDenied: Boolean = false,
/** Secret-only: the env var the value will be stored under. */
val envVar: String? = null,
/**
* Upstream blocking timeout (clarify/secret 300s, sudo 120s). 0 means no
* countdown — approvals are session-scoped and never expire on their own.
* Server-advertised blocking timeout. 0 means no client countdown; the
* authoritative `*.expire` event still retires the interaction.
*/
val timeoutSeconds: Int,
) {
@@ -432,6 +432,7 @@ private class RetryingEventSource(
class HermesApiClient(
baseUrl: String,
private val apiKey: String,
httpClient: OkHttpClient? = null,
private val json: Json = Json {
ignoreUnknownKeys = true
isLenient = true
@@ -479,7 +480,7 @@ class HermesApiClient(
private val mainHandler = Handler(Looper.getMainLooper())
private val client: OkHttpClient = OkHttpClient.Builder()
private val client: OkHttpClient = httpClient ?: OkHttpClient.Builder()
.readTimeout(5, TimeUnit.MINUTES)
.connectTimeout(10, TimeUnit.SECONDS)
.build()
@@ -16,6 +16,7 @@ import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
import java.time.Instant
/**
@@ -76,6 +77,26 @@ object FlexibleIdNonNullSerializer : KSerializer<String> {
}
}
/** Unknown-safe durable SQLite row id used by current Gateway history. */
@OptIn(ExperimentalSerializationApi::class)
object FlexibleLongSerializer : KSerializer<Long?> {
override val descriptor = PrimitiveSerialDescriptor("FlexibleLong", PrimitiveKind.LONG)
override fun deserialize(decoder: Decoder): Long? {
return try {
val jsonDecoder = decoder as? JsonDecoder
?: return decoder.decodeLong()
(jsonDecoder.decodeJsonElement() as? JsonPrimitive)?.longOrNull
} catch (_: Exception) {
null
}
}
override fun serialize(encoder: Encoder, value: Long?) {
if (value != null) encoder.encodeLong(value) else encoder.encodeNull()
}
}
/** Timestamp serializer for Hermes session metadata.
*
* Upstream currently returns epoch seconds for `started_at` / `last_active`;
@@ -170,11 +191,39 @@ data class SessionItem(
/** Durable flags returned by current Dashboard and API-server session resources. */
val pinned: Boolean = false,
val archived: Boolean = false,
/** Optional workspace metadata added by newer Dashboard session lists. */
val cwd: String? = null,
@SerialName("git_branch") val gitBranch: String? = null,
@SerialName("git_repo_root") val gitRepoRoot: String? = null,
/** Best-effort association from the Dashboard's read-only transcript scan. */
val pullRequest: SessionPullRequest? = null,
) {
val resolvedLastActivity: Double?
get() = lastActive ?: lastActivity ?: lastActivityAt ?: updatedAt
}
@Serializable
data class SessionPullRequest(
val number: Int,
val url: String,
val branch: String? = null,
val state: String? = null,
val draft: Boolean = false,
val title: String? = null,
)
@Serializable
data class SessionPullRequestScanResponse(
@SerialName("pull_requests") val pullRequests: Map<String, SessionPullRequest> = emptyMap(),
val scanned: List<String> = emptyList(),
)
@Serializable
data class RepositoryPullRequestListResponse(
val ghReady: Boolean = false,
val prs: List<SessionPullRequest> = emptyList(),
)
@Serializable
data class CreateSessionRequest(
val title: String? = null,
@@ -265,6 +314,9 @@ data class MessageItem(
@SerialName("session_id")
@Serializable(with = FlexibleIdSerializer::class)
val sessionId: String? = null,
@SerialName("row_id")
@Serializable(with = FlexibleLongSerializer::class)
val rowId: Long? = null,
val role: String,
val content: JsonElement? = null,
@SerialName("tool_calls") val toolCalls: JsonElement? = null,
@@ -618,21 +618,11 @@ fun RelayApp() {
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
val relayVoiceReady by connectionViewModel.relayVoiceReady.collectAsState()
// Profile Inspector client. Shares the same lazy relay URL + bearer
// token providers as the voice client so any rotation/re-pair is
// automatically picked up on the next fetch. Process-stable via
// remember {} so the OkHttpClient isn't rebuilt on recomposition.
val profileInspectorClient = remember {
RelayProfileInspectorClient(
okHttpClient = okhttp3.OkHttpClient.Builder()
.readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.build(),
relayUrlProvider = { connectionViewModel.effectiveRelayUrl.value },
sessionTokenProvider = {
(connectionViewModel.authState.value as? AuthState.Paired)?.token
},
)
val profileInspectorHttpClient = remember {
okhttp3.OkHttpClient.Builder()
.readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.build()
}
// === PHASE3-status: sync granular phone-status settings to chat ===
val appContextEnabled by connectionViewModel.appContextEnabled.collectAsState()
@@ -2619,7 +2609,8 @@ fun RelayApp() {
val sectionArg = backStackEntry.arguments
?.getString(Screen.ProfileInspector.ARG_SECTION)
?: Screen.ProfileInspector.SECTION_CONFIG
if (coldStartAuthState !is AuthState.Paired) {
val inspectorGatewayClient = connectionViewModel.activeGatewayChatClient()
if (coldStartAuthState !is AuthState.Paired && inspectorGatewayClient == null) {
PowerFeatureGateScreen(
title = stringResource(R.string.screen_profile_inspector_label),
summary = stringResource(R.string.power_gate_profile_inspector_summary),
@@ -2647,8 +2638,18 @@ fun RelayApp() {
// SavedStateHandle contains our
// `profileName` arg automatically.
val ssh = extras.createSavedStateHandle()
// Freeze both transports to the connection that
// owned this nav entry. A later connection/profile
// switch cannot redirect an open editor's writes.
val relayUrl = connectionViewModel.effectiveRelayUrl.value
val relayToken = (connectionViewModel.authState.value as? AuthState.Paired)?.token
return ProfileInspectorViewModel(
client = profileInspectorClient,
legacyClient = RelayProfileInspectorClient(
okHttpClient = profileInspectorHttpClient,
relayUrlProvider = { relayUrl },
sessionTokenProvider = { relayToken },
),
gatewayClient = inspectorGatewayClient,
savedStateHandle = ssh,
) as T
}
@@ -105,6 +105,11 @@ import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.ConnectionValidation
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.hasSecureProxy
import com.hermesandroid.relay.data.hasHermesReach
import com.hermesandroid.relay.data.presentationRouteUrl
import com.hermesandroid.relay.data.secureLinkCoversAllServices
import com.hermesandroid.relay.data.secureLinkServices
import com.hermesandroid.relay.data.primaryRouteUrl
import com.hermesandroid.relay.network.shared.HermesLanDiscovery
import com.hermesandroid.relay.network.shared.HermesLanDiscoveryResult
@@ -3174,7 +3179,7 @@ private fun ConfirmStep(
// app auto-falls back to the secure one, so a blanket "Insecure (dev)"
// badge from endpoint[0] alone would lie to the user.
val anySecure = endpoints.any { c ->
c.relay?.url?.startsWith("wss://") == true || c.api?.tls == true ||
c.hasSecureProxy() || c.relay?.url?.startsWith("wss://") == true || c.api?.tls == true ||
c.relay?.transportHint.equals("wss", ignoreCase = true) ||
c.dashboard?.url?.startsWith("https://", ignoreCase = true) == true
}
@@ -3195,7 +3200,7 @@ private fun ConfirmStep(
// Mixed case ("Tailscale is encrypted..." vs "Public is encrypted...").
val firstSecureLabel = endpoints
.firstOrNull { c ->
c.relay?.url?.startsWith("wss://") == true || c.api?.tls == true ||
c.hasSecureProxy() || c.relay?.url?.startsWith("wss://") == true || c.api?.tls == true ||
c.relay?.transportHint.equals("wss", ignoreCase = true) ||
c.dashboard?.url?.startsWith("https://", ignoreCase = true) == true
}?.displayLabel()
@@ -3208,6 +3213,7 @@ private fun ConfirmStep(
val distinctRoles = endpoints.map { it.role }.distinct()
var preferRole by remember(payload) { mutableStateOf<String?>(null) }
var preferMenuOpen by remember { mutableStateOf(false) }
val secureLink = endpoints.firstOrNull { it.hasSecureProxy() }
Column(
verticalArrangement = Arrangement.spacedBy(14.dp),
@@ -3318,6 +3324,15 @@ private fun ConfirmStep(
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
secureLink?.let { route ->
SecureLinkPairingSummary(
services = route.secureLinkServices(),
complete = route.secureLinkCoversAllServices(),
hasFallback = endpoints.size > 1,
usesReach = route.hasHermesReach(),
)
HorizontalDivider()
}
endpoints.forEachIndexed { index, candidate ->
if (index > 0) HorizontalDivider()
EndpointPreviewRow(
@@ -3720,7 +3735,7 @@ private fun EndpointPreviewRow(
) {
// Per-row security derived from the same three signals as the overall
// securityState computation — scheme, tls flag, transportHint.
val isSecure = candidate.relay?.url?.startsWith("wss://") == true ||
val isSecure = candidate.hasSecureProxy() || candidate.relay?.url?.startsWith("wss://") == true ||
candidate.api?.tls == true ||
candidate.relay?.transportHint.equals("wss", ignoreCase = true) ||
candidate.dashboard?.url?.startsWith("https://", ignoreCase = true) == true
@@ -3756,7 +3771,7 @@ private fun EndpointPreviewRow(
}
}
Text(
text = candidate.primaryRouteUrl().orEmpty() +
text = candidate.presentationRouteUrl().orEmpty() +
(candidate.relay?.transportHint?.let { " \u00b7 $it" } ?: ""),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
@@ -3772,6 +3787,75 @@ private fun EndpointPreviewRow(
}
}
@Composable
private fun SecureLinkPairingSummary(
services: List<String>,
complete: Boolean,
hasFallback: Boolean,
usesReach: Boolean,
) {
val relayLabel = stringResource(R.string.secure_link_service_relay)
val apiLabel = stringResource(R.string.secure_link_service_api)
val dashboardLabel = stringResource(R.string.secure_link_service_dashboard)
val serviceText = services.map { service ->
when (service) {
"relay" -> relayLabel
"api" -> apiLabel
"dashboard" -> dashboardLabel
else -> service
}
}.joinToString(" · ")
Surface(
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.08f),
shape = RoundedCornerShape(12.dp),
) {
Column(
modifier = Modifier.fillMaxWidth().padding(12.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text(
stringResource(if (usesReach) R.string.hermes_reach_title else R.string.secure_link_title),
style = MaterialTheme.typography.titleSmall,
)
if (usesReach) {
Text(
stringResource(R.string.hermes_reach_summary),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(
stringResource(R.string.secure_link_pinned_tls),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
)
Text(
if (serviceText.isBlank()) stringResource(R.string.secure_link_no_services)
else stringResource(R.string.secure_link_protects, serviceText),
style = MaterialTheme.typography.bodySmall,
)
if (!complete) {
Text(
stringResource(R.string.secure_link_partial_warning),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
Text(
if (hasFallback) stringResource(R.string.secure_link_fallback_ready)
else stringResource(R.string.secure_link_no_fallback),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
stringResource(R.string.secure_link_auth_note),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
/**
* Compact pill used by [EndpointPreviewRow] — matches the "Preferred" soft
* chip style so the row reads as a row of related chips rather than a mix
@@ -57,6 +57,9 @@ import com.hermesandroid.relay.data.Connection
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.SurfaceSecurityKind
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.hasSecureProxy
import com.hermesandroid.relay.data.secureLinkCoversAllServices
import com.hermesandroid.relay.data.secureLinkServices
import com.hermesandroid.relay.data.isEncryptedOverlayRoute
import com.hermesandroid.relay.data.isKnownRole
import com.hermesandroid.relay.data.isTlsUrl
@@ -323,6 +326,9 @@ private fun EndpointRow(
val apiLabel = stringResource(R.string.active_section_api_server)
val relayLabel = stringResource(R.string.active_section_relay)
val surfaceSummary = listOfNotNull(
candidate.proxy?.takeIf { candidate.hasSecureProxy() }?.let {
stringResource(R.string.secure_link_pinned_tls_short)
},
dashboardSurfaceUrl?.let { "$dashboardLabel ${displayPort(it)}" },
candidate.api?.url?.let { "$apiLabel ${displayPort(it)}" },
candidate.relay?.url?.let { "$relayLabel ${displayPort(it)}" },
@@ -357,6 +363,36 @@ private fun EndpointRow(
)
}
}
if (candidate.hasSecureProxy()) {
val secureRelayLabel = stringResource(R.string.secure_link_service_relay)
val secureApiLabel = stringResource(R.string.secure_link_service_api)
val secureDashboardLabel = stringResource(R.string.secure_link_service_dashboard)
val services = candidate.secureLinkServices().map { service ->
when (service) {
"relay" -> secureRelayLabel
"api" -> secureApiLabel
"dashboard" -> secureDashboardLabel
else -> service
}
}.joinToString(" · ")
Text(
text = stringResource(R.string.secure_link_protects, services),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
if (!candidate.secureLinkCoversAllServices()) {
Text(
text = stringResource(R.string.secure_link_partial_warning),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
Text(
text = stringResource(R.string.secure_link_auth_note),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
// 3-dot overflow menu — actions per-row so the card stays flat
@@ -680,6 +716,7 @@ private fun roleIcon(role: String): ImageVector = when (role.lowercase()) {
* be classified independently before it's the active route.
*/
private fun EndpointCandidate.routeSecurityKind(): SurfaceSecurityKind = when {
hasSecureProxy() -> SurfaceSecurityKind.Tls
isTlsUrl(primaryRouteUrl().orEmpty()) -> SurfaceSecurityKind.Tls
isEncryptedOverlayRoute(isTailscaleDetected = false) -> SurfaceSecurityKind.Overlay
else -> SurfaceSecurityKind.Plain
@@ -45,6 +45,8 @@ import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@ -81,6 +83,7 @@ import com.hermesandroid.relay.data.HermesCardAction
import com.hermesandroid.relay.data.HermesCardDispatch
import com.hermesandroid.relay.data.HermesCardField
import com.hermesandroid.relay.data.HermesCardInput
import com.hermesandroid.relay.data.encodeClarifyMultiSelectAnswer
import com.hermesandroid.relay.ui.theme.RelayRefresh
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
import kotlinx.coroutines.coroutineScope
@@ -389,7 +392,8 @@ private fun ChoseRow(
/**
* The interactive answer surface for ask cards, composed from the
* [HermesCardInput] flags rather than the card type:
* - [HermesCardInput.choices] → AssistChip row, one tap dispatches.
* - [HermesCardInput.choices] → one-tap AssistChips, or independently
* selected FilterChips plus explicit submit for multi-select clarifies.
* - [HermesCardInput.allowFreeText] → [InlineAnswerField] mini pill +
* 18dp send affordance.
* - [HermesCardInput.masked] → password-style OutlinedTextField with a
@@ -411,6 +415,8 @@ private fun CardInputSlot(
// never be written into the saved-instance-state Bundle.
var answerText by remember { mutableStateOf("") }
var reveal by remember { mutableStateOf(false) }
var selectedChoices by remember(input.choices) { mutableStateOf(emptyList<String>()) }
val isMultiSelect = input.multiSelect && input.choices.isNotEmpty()
val showFreeText = !input.masked && (
input.allowFreeText ||
@@ -428,16 +434,45 @@ private fun CardInputSlot(
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
input.choices.forEach { choice ->
AssistChip(
onClick = { onSubmit(choice) },
label = {
Text(choice, style = MaterialTheme.typography.labelMedium)
},
colors = AssistChipDefaults.assistChipColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerHighest,
labelColor = MaterialTheme.colorScheme.onSurface,
),
)
if (isMultiSelect) {
val selected = choice in selectedChoices
FilterChip(
selected = selected,
onClick = {
selectedChoices = if (selected) {
selectedChoices - choice
} else {
selectedChoices + choice
}
},
label = { Text(choice, style = MaterialTheme.typography.labelMedium) },
leadingIcon = if (selected) {
{
Icon(
Icons.Filled.Check,
contentDescription = null,
modifier = Modifier.size(16.dp),
)
}
} else {
null
},
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.secondaryContainer,
),
)
} else {
AssistChip(
onClick = { onSubmit(choice) },
label = {
Text(choice, style = MaterialTheme.typography.labelMedium)
},
colors = AssistChipDefaults.assistChipColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerHighest,
labelColor = MaterialTheme.colorScheme.onSurface,
),
)
}
}
}
}
@@ -482,21 +517,38 @@ private fun CardInputSlot(
onValueChange = { answerText = it },
modifier = Modifier.weight(1f),
)
IconButton(
onClick = { onSubmit(answerText.trim()) },
enabled = answerText.isNotBlank(),
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.Send,
contentDescription = stringResource(R.string.card_send_answer_a11y),
tint = if (answerText.isNotBlank()) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp),
)
if (!isMultiSelect) {
IconButton(
onClick = { onSubmit(answerText.trim()) },
enabled = answerText.isNotBlank(),
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.Send,
contentDescription = stringResource(R.string.card_send_answer_a11y),
tint = if (answerText.isNotBlank()) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp),
)
}
}
}
}
if (isMultiSelect) {
val answers = selectedChoices +
listOfNotNull(answerText.trim().takeIf(String::isNotEmpty))
Spacer(Modifier.height(10.dp))
Button(
onClick = { onSubmit(encodeClarifyMultiSelectAnswer(answers)) },
enabled = answers.isNotEmpty(),
) {
Text(
stringResource(R.string.card_submit),
style = MaterialTheme.typography.labelMedium,
)
}
}
// Submit affordance for masked / hold-to-confirm inputs
when {
input.holdToConfirm -> {
@@ -104,6 +104,25 @@ data class ProfileSessionRow(
val session: ChatSession,
)
internal fun sessionWorkLabels(session: ChatSession): List<String> = buildList {
val repo = (session.gitRepoRoot ?: session.workingDirectory)
?.trimEnd('/', '\\')
?.substringAfterLast('/')
?.substringAfterLast('\\')
?.takeIf { it.isNotBlank() }
repo?.let(::add)
session.gitBranch?.trim()?.takeIf { it.isNotBlank() }?.let(::add)
session.pullRequestNumber?.takeIf { it > 0 }?.let { number ->
val status = when {
session.pullRequestDraft -> "Draft"
!session.pullRequestState.isNullOrBlank() ->
session.pullRequestState.lowercase().replaceFirstChar { it.uppercaseChar() }
else -> null
}
add(listOfNotNull("PR #$number", status).joinToString(" · "))
}
}
internal fun sessionPinIcon(pinned: Boolean) =
if (pinned) Icons.Filled.Star else Icons.Outlined.StarBorder
@@ -206,7 +225,8 @@ fun SessionDrawerContent(
needle.isBlank() ||
session.sessionId.contains(needle, ignoreCase = true) ||
session.title.orEmpty().contains(needle, ignoreCase = true) ||
session.model.orEmpty().contains(needle, ignoreCase = true)
session.model.orEmpty().contains(needle, ignoreCase = true) ||
sessionWorkLabels(session).any { it.contains(needle, ignoreCase = true) }
}
.sortedWith(
compareByDescending<ChatSession> { it.pinned }
@@ -648,7 +668,8 @@ fun SessionDrawerContent(
needle.isBlank() ||
row.profile.contains(needle, ignoreCase = true) ||
row.session.title.orEmpty().contains(needle, ignoreCase = true) ||
row.session.sessionId.contains(needle, ignoreCase = true)
row.session.sessionId.contains(needle, ignoreCase = true) ||
sessionWorkLabels(row.session).any { it.contains(needle, ignoreCase = true) }
}
AlertDialog(
onDismissRequest = { allProfilesOpen = false },
@@ -693,6 +714,15 @@ fun SessionDrawerContent(
style = relayMetadataStyle(),
color = RelayRefresh.Relay,
)
sessionWorkLabels(row.session).takeIf { it.isNotEmpty() }?.let { labels ->
Text(
labels.joinToString(" • "),
style = relayMetadataStyle(),
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
@@ -771,6 +801,28 @@ private fun SessionItem(
MaterialTheme.colorScheme.onSurface
}
)
val workLabels = sessionWorkLabels(session)
if (workLabels.isNotEmpty()) {
Row(
horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier
.padding(top = 4.dp)
.horizontalScroll(rememberScrollState()),
) {
workLabels.forEach { label ->
Text(
text = label,
style = relayMetadataStyle(),
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.background(MaterialTheme.colorScheme.surfaceVariant)
.padding(horizontal = 6.dp, vertical = 1.dp),
)
}
}
}
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -2139,6 +2139,13 @@ fun ChatScreen(
source = item.source,
pinned = item.pinned,
archived = item.archived,
workingDirectory = item.cwd,
gitBranch = item.gitBranch,
gitRepoRoot = item.gitRepoRoot,
pullRequestNumber = item.pullRequest?.number,
pullRequestUrl = item.pullRequest?.url,
pullRequestState = item.pullRequest?.state,
pullRequestDraft = item.pullRequest?.draft == true,
),
)
}
@@ -54,6 +54,14 @@ internal enum class DashboardActionKind {
ValidateCustomEndpoint,
ActivateCustomEndpoint,
DeleteCustomEndpoint,
EditLearningNode,
DeleteLearningNode,
ConfigureMemoryProvider,
ActivateMemoryProvider,
SetupWhatsApp,
EnableChannel,
DisableChannel,
TestChannel,
// Input-backed kinds — intercepted before runAction and routed to a
// text-input or model-picker dialog instead of firing immediately.
@@ -3,11 +3,16 @@
package com.hermesandroid.relay.ui.screens
import android.content.Intent
import android.content.ContentResolver
import android.graphics.Bitmap
import android.net.Uri
import android.provider.OpenableColumns
import android.webkit.CookieManager
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
@@ -35,6 +40,7 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.Image
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
@@ -90,6 +96,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
@@ -125,16 +132,24 @@ import com.hermesandroid.relay.viewmodel.PendingMcpOAuth
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.text.DateFormat
import java.util.Date
import java.io.IOException
import com.google.zxing.BarcodeFormat
import com.google.zxing.qrcode.QRCodeWriter
/**
* Section of the Hermes dashboard Manage tab. The enum identity is used for
@@ -248,7 +263,10 @@ internal fun scopeDashboardManageItems(
if (
sectionPath == "/api/mcp/servers" ||
sectionPath == "/api/mcp/catalog" ||
sectionPath == "/api/providers/custom-endpoints"
sectionPath == "/api/providers/custom-endpoints" ||
sectionPath == "/api/learning/graph" ||
sectionPath == "/api/memory" ||
sectionPath == "/api/messaging/platforms"
) {
items.map { it.copy(profile = profile) }
} else {
@@ -375,6 +393,9 @@ private enum class DashboardSectionAction {
UpdateSkillsHub,
AddCustomEndpoint,
CreateServerBackup,
DownloadServerBackup,
ImportServerBackup,
SetupWhatsApp,
}
/** Editor session for a profile's SOUL.md — content is the FULL file from GET. */
@@ -384,6 +405,28 @@ private data class SoulEditorState(
val exists: Boolean,
)
private data class LearningEditorState(
val id: String,
val title: String,
val initialContent: String,
val profile: String?,
)
private data class MemoryProviderEditorState(
val name: String,
val schema: JsonObject,
val profile: String?,
)
private data class WhatsAppOnboardingState(
val pairingId: String,
val status: String,
val qrPayload: String?,
val mode: String,
val allowedUsers: String,
val error: String? = null,
)
/** Which config slot a model-picker selection writes to. */
private sealed interface ModelPickerTarget {
data object Main : ModelPickerTarget
@@ -424,6 +467,9 @@ fun DashboardManagementScreen(
val pendingMcpOAuth by oauthViewModel.pending.collectAsState()
val unsupportedOAuthRoutes by oauthViewModel.unsupportedRoutes.collectAsState()
val supportedOAuthRoutes by oauthViewModel.supportedRoutes.collectAsState()
val clientFactory = remember(dashboardUrl, connectionViewModel) {
{ connectionViewModel.dashboardClientForActive(dashboardUrl) }
}
var selectedTab by remember { mutableStateOf(0) }
var showingDetail by remember { mutableStateOf(false) }
var reloadNonce by remember { mutableStateOf(0) }
@@ -446,6 +492,66 @@ fun DashboardManagementScreen(
var oauthDialogHidden by remember(pendingMcpOAuth?.flowId) { mutableStateOf(false) }
var customEndpointEditor by remember { mutableStateOf<DashboardSummaryItem?>(null) }
var showCustomEndpointEditor by remember { mutableStateOf(false) }
var learningEditor by remember { mutableStateOf<LearningEditorState?>(null) }
var memoryProviderEditor by remember { mutableStateOf<MemoryProviderEditorState?>(null) }
var showWhatsAppSetup by remember { mutableStateOf(false) }
var whatsappOnboarding by remember { mutableStateOf<WhatsAppOnboardingState?>(null) }
var backupArchive by remember { mutableStateOf<String?>(null) }
var importArchiveInput by remember { mutableStateOf(false) }
var pendingBackupDownload by remember { mutableStateOf<String?>(null) }
val backupSaveLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.CreateDocument("application/zip"),
) { uri ->
val archive = pendingBackupDownload
pendingBackupDownload = null
if (uri != null && archive != null) scope.launch {
actionInFlight = true
withDashboardClient(clientFactory) {
it.downloadServerBackup(archive) {
context.contentResolver.openOutputStream(uri)
?: throw IOException("The selected destination could not be opened.")
}
}.fold(
onSuccess = { actionMessage = context.getString(R.string.dashboard_backup_saved, it) },
onFailure = {
withContext(Dispatchers.IO) { runCatching { context.contentResolver.delete(uri, null, null) } }
actionMessage = it.message ?: context.getString(R.string.dashboard_backup_download_failed)
},
)
actionInFlight = false
}
}
val backupImportLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.OpenDocument(),
) { uri ->
if (uri != null) scope.launch {
actionInFlight = true
val metadata = runCatching {
withContext(Dispatchers.IO) {
dashboardImportMetadata(context.contentResolver, uri)
}
}
metadata.fold(
onSuccess = { file ->
withDashboardClient(clientFactory) {
it.uploadServerBackup(
filename = file.name,
contentLength = file.length,
openStream = {
context.contentResolver.openInputStream(uri)
?: throw IOException("The selected archive could not be opened.")
},
)
}.fold(
onSuccess = { actionMessage = context.getString(R.string.dashboard_import_started) },
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_import_failed) },
)
},
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_import_failed) },
)
actionInFlight = false
}
}
val section = managementSections[selectedTab]
val connectionId = activeConnection?.id ?: "default"
@@ -490,10 +596,6 @@ fun DashboardManagementScreen(
)
}
}
val clientFactory = remember(dashboardUrl, connectionViewModel) {
{ connectionViewModel.dashboardClientForActive(dashboardUrl) }
}
suspend fun loadDashboardSection(
targetSection: DashboardManagementSection,
targetKey: String,
@@ -828,9 +930,10 @@ fun DashboardManagementScreen(
}
actionMessage = result.fold(
onSuccess = { root ->
backupArchive = root.stringField("archive")
root.stringField("message")
?: root.stringField("filename")?.let { "Server backup ready: $it" }
?: "Server backup created."
?: root.stringField("archive")?.let { "Server backup started: $it" }
?: "Server backup started."
},
onFailure = { error -> error.message ?: "Server backup failed." },
)
@@ -838,6 +941,41 @@ fun DashboardManagementScreen(
}
}
fun openLearningEditor(item: DashboardSummaryItem) {
if (actionInFlight) return
actionInFlight = true
scope.launch {
val result = withDashboardClient(clientFactory) { it.getLearningNode(item.id, effectiveProfileName) }
result.fold(
onSuccess = { root ->
learningEditor = LearningEditorState(
id = item.id,
title = item.title,
initialContent = root.stringField("content").orEmpty(),
profile = effectiveProfileName,
)
},
onFailure = { actionMessage = it.message ?: "Learning node could not be loaded." },
)
actionInFlight = false
}
}
fun openMemoryProvider(item: DashboardSummaryItem) {
if (actionInFlight) return
actionInFlight = true
scope.launch {
val result = withDashboardClient(clientFactory) {
it.getMemoryProviderConfig(item.id, effectiveProfileName)
}
result.fold(
onSuccess = { memoryProviderEditor = MemoryProviderEditorState(item.id, it, effectiveProfileName) },
onFailure = { actionMessage = it.message ?: "Memory provider configuration could not be loaded." },
)
actionInFlight = false
}
}
LaunchedEffect(dashboardUrl, selectedTab, reloadNonce, activeConnection?.id, effectiveProfileName) {
val forceCurrent = forceReloadKey == payloadKey
loadDashboardSection(
@@ -909,6 +1047,7 @@ fun DashboardManagementScreen(
pendingAction?.let { pending ->
val isActivateProfile = pending.action.kind == DashboardActionKind.ActivateProfile
val isDeleteLearning = pending.action.kind == DashboardActionKind.DeleteLearningNode
val actionLabel = dashboardActionLabel(pending.action)
AlertDialog(
onDismissRequest = { pendingAction = null },
@@ -922,6 +1061,8 @@ fun DashboardManagementScreen(
Text(
text = if (isActivateProfile) {
stringResource(R.string.dashboard_activate_profile_body, pending.item.title)
} else if (isDeleteLearning) {
stringResource(R.string.dashboard_learning_delete_warning)
} else {
stringResource(R.string.dashboard_generic_action_body, pending.item.title)
},
@@ -1354,6 +1495,9 @@ fun DashboardManagementScreen(
)
DashboardActionKind.EditProfileSoul ->
openSoulEditor(item)
DashboardActionKind.EditLearningNode -> openLearningEditor(item)
DashboardActionKind.ConfigureMemoryProvider -> openMemoryProvider(item)
DashboardActionKind.SetupWhatsApp -> showWhatsAppSetup = true
DashboardActionKind.AuthenticateMcp ->
if (mcpOAuthStartAllowed) {
oauthDialogHidden = false
@@ -1370,7 +1514,9 @@ fun DashboardManagementScreen(
// per-conversation switch in chat.
DashboardActionKind.ActivateProfile,
DashboardActionKind.ActivateCustomEndpoint,
DashboardActionKind.DeleteCustomEndpoint ->
DashboardActionKind.DeleteCustomEndpoint,
DashboardActionKind.ActivateMemoryProvider,
DashboardActionKind.DeleteLearningNode ->
pendingAction = PendingDashboardAction(item, action)
else -> if (action.destructive) {
pendingAction = PendingDashboardAction(item, action)
@@ -1395,6 +1541,20 @@ fun DashboardManagementScreen(
}
DashboardSectionAction.CreateServerBackup ->
runServerBackup()
DashboardSectionAction.DownloadServerBackup -> {
val archive = backupArchive
if (archive == null) {
actionMessage = context.getString(R.string.dashboard_backup_create_first)
} else {
pendingBackupDownload = archive
backupSaveLauncher.launch(
archive.substringAfterLast('/').substringAfterLast('\\')
.ifBlank { "hermes-backup.zip" },
)
}
}
DashboardSectionAction.ImportServerBackup -> importArchiveInput = true
DashboardSectionAction.SetupWhatsApp -> showWhatsAppSetup = true
}
},
mcpOAuthSupported = mcpOAuthStartAllowed,
@@ -1432,6 +1592,141 @@ fun DashboardManagementScreen(
}
}
}
learningEditor?.let { editor ->
TextDocumentEditorDialog(
title = context.getString(R.string.dashboard_learning_edit_title, editor.title),
initialContent = editor.initialContent,
warning = context.getString(R.string.dashboard_learning_edit_warning),
saving = actionInFlight,
onSave = { content ->
scope.launch {
actionInFlight = true
withDashboardClient(clientFactory) {
it.updateLearningNode(editor.id, content, editor.profile)
}.fold(
onSuccess = {
learningEditor = null
forceReloadKey = payloadKey
reloadNonce += 1
actionMessage = context.getString(R.string.dashboard_learning_saved)
},
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_learning_save_failed) },
)
actionInFlight = false
}
},
onDismiss = { learningEditor = null },
)
}
memoryProviderEditor?.let { editor ->
MemoryProviderDialog(
editor = editor,
saving = actionInFlight,
onSubmit = { rawValues, setup ->
val values = if (setup) JsonObject(emptyMap())
else runCatching { Json.parseToJsonElement(rawValues).jsonObject }.getOrNull()
if (!setup && values == null) {
actionMessage = context.getString(R.string.dashboard_memory_invalid_json)
} else scope.launch {
actionInFlight = true
val result = withDashboardClient(clientFactory) { client ->
if (setup) client.setupMemoryProvider(editor.name)
else client.updateMemoryProviderConfig(editor.name, checkNotNull(values), editor.profile)
}
result.fold(
onSuccess = {
memoryProviderEditor = null
forceReloadKey = payloadKey
reloadNonce += 1
actionMessage = if (setup) context.getString(R.string.dashboard_memory_setup_started)
else context.getString(R.string.dashboard_memory_saved)
},
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_memory_save_failed) },
)
actionInFlight = false
}
},
onDismiss = { memoryProviderEditor = null },
)
}
if (importArchiveInput) {
AlertDialog(
onDismissRequest = { importArchiveInput = false },
title = { Text(stringResource(R.string.dashboard_import_title)) },
text = { Text(stringResource(R.string.dashboard_import_warning)) },
confirmButton = {
Button(
onClick = {
importArchiveInput = false
backupImportLauncher.launch(arrayOf("application/zip", "application/octet-stream"))
},
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
) { Text(stringResource(R.string.dashboard_import_confirm)) }
},
dismissButton = {
TextButton(onClick = { importArchiveInput = false }) { Text(stringResource(R.string.dashboard_cancel)) }
},
)
}
if (showWhatsAppSetup) {
WhatsAppSetupDialog(
onboarding = whatsappOnboarding,
busy = actionInFlight,
onStart = { mode, allowed ->
scope.launch {
actionInFlight = true
withDashboardClient(clientFactory) {
it.startWhatsAppOnboarding(mode, allowed, effectiveProfileName)
}.fold(
onSuccess = { root -> whatsappOnboarding = root.toWhatsAppOnboarding(mode, allowed) },
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_whatsapp_start_failed) },
)
actionInFlight = false
}
},
onApply = { state ->
scope.launch {
actionInFlight = true
withDashboardClient(clientFactory) {
it.applyWhatsAppOnboarding(state.pairingId, state.mode, state.allowedUsers, effectiveProfileName)
}.fold(
onSuccess = {
showWhatsAppSetup = false
whatsappOnboarding = null
forceReloadKey = payloadKey
reloadNonce += 1
actionMessage = context.getString(R.string.dashboard_whatsapp_saved)
},
onFailure = { actionMessage = it.message ?: context.getString(R.string.dashboard_whatsapp_apply_failed) },
)
actionInFlight = false
}
},
onDismiss = {
whatsappOnboarding?.pairingId?.let { pairingId ->
scope.launch { withDashboardClient(clientFactory) { it.cancelWhatsAppOnboarding(pairingId) } }
}
whatsappOnboarding = null
showWhatsAppSetup = false
},
)
}
LaunchedEffect(whatsappOnboarding?.pairingId, whatsappOnboarding?.status) {
val pairingId = whatsappOnboarding?.pairingId ?: return@LaunchedEffect
while (true) {
val current = whatsappOnboarding ?: break
if (current.pairingId != pairingId || current.status in setOf("connected", "error", "expired", "cancelled")) break
delay(1_500)
withDashboardClient(clientFactory) { it.getWhatsAppOnboarding(pairingId) }
.onSuccess { whatsappOnboarding = it.toWhatsAppOnboarding(current.mode, current.allowedUsers) }
.onFailure { whatsappOnboarding = current.copy(status = "error", error = it.message) }
}
}
}
private data class ManageTileSpec(
@@ -2296,6 +2591,9 @@ private fun LoadedBody(
val actionLabelUpdateInstalled = stringResource(R.string.dashboard_section_action_update_installed)
val actionLabelAddEndpoint = stringResource(R.string.dashboard_custom_endpoint_add)
val actionLabelServerBackup = stringResource(R.string.dashboard_section_action_server_backup)
val actionLabelDownloadBackup = stringResource(R.string.dashboard_section_action_download_backup)
val actionLabelImportBackup = stringResource(R.string.dashboard_section_action_import_backup)
val actionLabelSetupWhatsApp = stringResource(R.string.dashboard_action_setup_whatsapp)
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = androidx.compose.foundation.layout.PaddingValues(
@@ -2325,6 +2623,11 @@ private fun LoadedBody(
)
DashboardManagementSection.Operations -> listOf(
DashboardSectionAction.CreateServerBackup to actionLabelServerBackup,
DashboardSectionAction.DownloadServerBackup to actionLabelDownloadBackup,
DashboardSectionAction.ImportServerBackup to actionLabelImportBackup,
)
DashboardManagementSection.Channels -> listOf(
DashboardSectionAction.SetupWhatsApp to actionLabelSetupWhatsApp,
)
else -> emptyList()
}
@@ -2420,6 +2723,14 @@ private fun dashboardActionLabel(kind: DashboardActionKind): String = when (kind
DashboardActionKind.ValidateCustomEndpoint -> stringResource(R.string.dashboard_action_validate)
DashboardActionKind.ActivateCustomEndpoint -> stringResource(R.string.dashboard_action_use)
DashboardActionKind.DeleteCustomEndpoint -> stringResource(R.string.dashboard_action_delete)
DashboardActionKind.EditLearningNode -> stringResource(R.string.dashboard_action_edit)
DashboardActionKind.DeleteLearningNode -> stringResource(R.string.dashboard_action_delete)
DashboardActionKind.ConfigureMemoryProvider -> stringResource(R.string.dashboard_action_configure)
DashboardActionKind.ActivateMemoryProvider -> stringResource(R.string.dashboard_action_use)
DashboardActionKind.SetupWhatsApp -> stringResource(R.string.dashboard_action_setup)
DashboardActionKind.EnableChannel -> stringResource(R.string.dashboard_action_enable)
DashboardActionKind.DisableChannel -> stringResource(R.string.dashboard_action_disable)
DashboardActionKind.TestChannel -> stringResource(R.string.dashboard_action_test)
}
/**
@@ -2454,6 +2765,14 @@ private fun dashboardActionLabel(context: android.content.Context, kind: Dashboa
DashboardActionKind.ValidateCustomEndpoint -> context.getString(R.string.dashboard_action_validate)
DashboardActionKind.ActivateCustomEndpoint -> context.getString(R.string.dashboard_action_use)
DashboardActionKind.DeleteCustomEndpoint -> context.getString(R.string.dashboard_action_delete)
DashboardActionKind.EditLearningNode -> context.getString(R.string.dashboard_action_edit)
DashboardActionKind.DeleteLearningNode -> context.getString(R.string.dashboard_action_delete)
DashboardActionKind.ConfigureMemoryProvider -> context.getString(R.string.dashboard_action_configure)
DashboardActionKind.ActivateMemoryProvider -> context.getString(R.string.dashboard_action_use)
DashboardActionKind.SetupWhatsApp -> context.getString(R.string.dashboard_action_setup)
DashboardActionKind.EnableChannel -> context.getString(R.string.dashboard_action_enable)
DashboardActionKind.DisableChannel -> context.getString(R.string.dashboard_action_disable)
DashboardActionKind.TestChannel -> context.getString(R.string.dashboard_action_test)
}
@OptIn(ExperimentalLayoutApi::class)
@@ -3793,14 +4112,32 @@ private fun summarize(
?.map { (name, value) -> summarizeObjectItem(value, name) }
?: listOf(summarizeObjectItem(root, "Profile"))
}
DashboardManagementSection.Memory -> summarizeKeyValueOrList(root, "Memory")
DashboardManagementSection.Memory -> summarizeMemoryProviders(root)
DashboardManagementSection.Learning ->
root.arrayItems("nodes", "items")
?.mapIndexed { index, item -> summarizeObjectItem(item, "Node ${index + 1}") }
?.mapIndexed { index, item ->
val summary = summarizeObjectItem(item, "Node ${index + 1}")
summary.copy(
actions = listOf(
DashboardItemAction("Edit", DashboardActionKind.EditLearningNode),
DashboardItemAction("Delete", DashboardActionKind.DeleteLearningNode, destructive = true),
),
)
}
?: summarizeKeyValueOrList(root, "Learning")
DashboardManagementSection.Channels ->
root.arrayItems("platforms", "channels", "items")
?.mapIndexed { index, item -> summarizeObjectItem(item, "Channel ${index + 1}") }
?.mapIndexed { index, item ->
val summary = summarizeObjectItem(item, "Channel ${index + 1}")
val enabled = (item as? JsonObject)?.booleanField("enabled") == true
summary.copy(actions = buildList {
add(DashboardItemAction(if (enabled) "Disable" else "Enable", if (enabled) DashboardActionKind.DisableChannel else DashboardActionKind.EnableChannel))
add(DashboardItemAction("Test", DashboardActionKind.TestChannel))
if (summary.id.equals("whatsapp", ignoreCase = true)) {
add(DashboardItemAction("Setup", DashboardActionKind.SetupWhatsApp))
}
})
}
?: summarizeKeyValueOrList(root, "Channel")
DashboardManagementSection.Operations -> summarizeKeyValueOrList(root, "Status")
DashboardManagementSection.Models -> summarizeKeyValueOrList(root, "Model")
@@ -3809,6 +4146,32 @@ private fun summarize(
}
}
private fun summarizeMemoryProviders(root: JsonElement): List<DashboardSummaryItem> {
val obj = root as? JsonObject ?: return emptyList()
val active = obj.stringField("active").orEmpty()
return obj.arrayItems("providers").orEmpty().mapIndexed { index, provider ->
val summary = summarizeObjectItem(provider, "Provider ${index + 1}")
val providerObj = provider as? JsonObject
val available = providerObj?.booleanField("available") != false
val configured = providerObj?.booleanField("configured") == true ||
providerObj?.booleanField("ready") == true
summary.copy(
meta = listOfNotNull(
if (summary.id == active) "active" else null,
if (available) "available" else "setup required",
summary.meta,
).joinToString(" · "),
actions = buildList {
add(DashboardItemAction("Configure", DashboardActionKind.ConfigureMemoryProvider))
if (summary.id != active && configured) {
add(DashboardItemAction("Use", DashboardActionKind.ActivateMemoryProvider))
}
},
)
}
}
/**
* `GET /api/env` returns a map of var name → metadata. Upstream's SPA hides
* `channel_managed` vars because its Channels page owns them — we have no
@@ -4064,6 +4427,14 @@ private fun DashboardSummaryItem.optimisticAfter(action: DashboardItemAction): D
from = DashboardActionKind.DisableMcp,
to = DashboardItemAction("Enable", DashboardActionKind.EnableMcp),
)
DashboardActionKind.EnableChannel -> withEnabledMeta(true).withActionSwap(
from = DashboardActionKind.EnableChannel,
to = DashboardItemAction("Disable", DashboardActionKind.DisableChannel),
)
DashboardActionKind.DisableChannel -> withEnabledMeta(false).withActionSwap(
from = DashboardActionKind.DisableChannel,
to = DashboardItemAction("Enable", DashboardActionKind.EnableChannel),
)
DashboardActionKind.PauseCron -> withActionSwap(
from = DashboardActionKind.PauseCron,
to = DashboardItemAction("Resume", DashboardActionKind.ResumeCron),
@@ -4075,7 +4446,8 @@ private fun DashboardSummaryItem.optimisticAfter(action: DashboardItemAction): D
DashboardActionKind.DeleteCron,
DashboardActionKind.RemoveMcp,
DashboardActionKind.DeleteProfile,
DashboardActionKind.DeleteCustomEndpoint -> null
DashboardActionKind.DeleteCustomEndpoint,
DashboardActionKind.DeleteLearningNode -> null
DashboardActionKind.InstallMcpCatalog -> copy(
meta = appendMeta(meta, "installed"),
actions = emptyList(),
@@ -4094,7 +4466,12 @@ private fun DashboardSummaryItem.optimisticAfter(action: DashboardItemAction): D
DashboardActionKind.RevealEnvKey,
DashboardActionKind.EditProfileDescription,
DashboardActionKind.SetProfileModel,
DashboardActionKind.EditProfileSoul -> this
DashboardActionKind.EditProfileSoul,
DashboardActionKind.EditLearningNode,
DashboardActionKind.ConfigureMemoryProvider,
DashboardActionKind.ActivateMemoryProvider,
DashboardActionKind.SetupWhatsApp,
DashboardActionKind.TestChannel -> this
DashboardActionKind.EditCustomEndpoint,
DashboardActionKind.ValidateCustomEndpoint,
DashboardActionKind.ActivateCustomEndpoint -> this
@@ -4226,6 +4603,11 @@ private suspend fun DashboardApiClient.runDashboardAction(
deleteCustomEndpoint(id, profile = item.profile).map { JsonObject(emptyMap()) }
DashboardActionKind.RevealEnvKey -> revealEnvVar(id)
DashboardActionKind.ClearEnvKey -> deleteEnvVar(id)
DashboardActionKind.DeleteLearningNode -> deleteLearningNode(id, item.profile)
DashboardActionKind.ActivateMemoryProvider -> activateMemoryProvider(id, item.profile)
DashboardActionKind.EnableChannel -> setMessagingPlatformEnabled(id, true, item.profile)
DashboardActionKind.DisableChannel -> setMessagingPlatformEnabled(id, false, item.profile)
DashboardActionKind.TestChannel -> testMessagingPlatform(id, item.profile)
// Input-backed kinds are intercepted at the onAction layer and routed
// to dialogs; reaching here means a wiring bug, not a server problem.
DashboardActionKind.SetEnvKey,
@@ -4233,6 +4615,10 @@ private suspend fun DashboardApiClient.runDashboardAction(
DashboardActionKind.SetProfileModel,
DashboardActionKind.EditProfileSoul ->
Result.failure(IllegalStateException("${action.label} requires input"))
DashboardActionKind.EditLearningNode,
DashboardActionKind.ConfigureMemoryProvider,
DashboardActionKind.SetupWhatsApp ->
Result.failure(IllegalStateException("${action.label} requires input"))
DashboardActionKind.EditCustomEndpoint,
DashboardActionKind.ValidateCustomEndpoint ->
Result.failure(IllegalStateException("${action.label} requires input"))
@@ -4294,3 +4680,192 @@ private fun compactJsonLines(root: JsonObject): String =
root.entries.joinToString("\n") { (key, value) ->
"$key: ${value.shortDisplay()}"
}.ifBlank { "{ }" }
private fun JsonObject.toWhatsAppOnboarding(mode: String, allowedUsers: String): WhatsAppOnboardingState =
WhatsAppOnboardingState(
pairingId = stringField("pairing_id").orEmpty(),
status = stringField("status").orEmpty(),
qrPayload = stringField("qr_payload"),
mode = stringField("mode") ?: mode,
allowedUsers = stringField("allowed_users") ?: allowedUsers,
error = stringField("error"),
)
private fun memoryInitialValues(schema: JsonObject): String {
val direct = schema["values"] as? JsonObject
if (direct != null) return Json { prettyPrint = true }.encodeToString(JsonObject.serializer(), direct)
val fields = schema["fields"] as? JsonArray ?: return "{}"
val values = buildJsonObject {
fields.forEach { element ->
val field = element as? JsonObject ?: return@forEach
val key = field.stringField("key") ?: return@forEach
field["value"]?.let { put(key, it) }
}
}
return Json { prettyPrint = true }.encodeToString(JsonObject.serializer(), values)
}
@Composable
private fun TextDocumentEditorDialog(
title: String,
initialContent: String,
warning: String,
saving: Boolean,
onSave: (String) -> Unit,
onDismiss: () -> Unit,
) {
var content by remember(initialContent) { mutableStateOf(initialContent) }
Dialog(onDismissRequest = { if (!saving) onDismiss() }) {
Card(modifier = Modifier.fillMaxWidth().heightIn(min = 360.dp, max = 680.dp)) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(title, style = MaterialTheme.typography.titleMedium)
Text(warning, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
OutlinedTextField(
value = content,
onValueChange = { content = it },
modifier = Modifier.fillMaxWidth().weight(1f),
textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
enabled = !saving,
)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
TextButton(onClick = onDismiss, enabled = !saving) { Text(stringResource(R.string.dashboard_cancel)) }
Button(onClick = { onSave(content) }, enabled = !saving && content.isNotBlank()) {
Text(stringResource(R.string.dashboard_save))
}
}
}
}
}
}
@Composable
private fun MemoryProviderDialog(
editor: MemoryProviderEditorState,
saving: Boolean,
onSubmit: (String, Boolean) -> Unit,
onDismiss: () -> Unit,
) {
var values by remember(editor) { mutableStateOf(memoryInitialValues(editor.schema)) }
val fields = editor.schema["fields"] as? JsonArray
AlertDialog(
onDismissRequest = { if (!saving) onDismiss() },
title = { Text(stringResource(R.string.dashboard_memory_config_title, editor.name)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(stringResource(R.string.dashboard_memory_config_help), style = MaterialTheme.typography.bodySmall)
if (!fields.isNullOrEmpty()) {
Text(fields.joinToString("\n") { field ->
val obj = field as? JsonObject
val key = obj?.stringField("key").orEmpty()
val label = obj?.stringField("label") ?: key
val required = if (obj?.booleanField("required") == true) " *" else ""
"$label$required"
}, style = MaterialTheme.typography.labelSmall)
}
OutlinedTextField(
value = values,
onValueChange = { values = it },
modifier = Modifier.fillMaxWidth().heightIn(min = 160.dp),
textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
enabled = !saving,
label = { Text(stringResource(R.string.dashboard_memory_values_json)) },
)
}
},
confirmButton = {
Button(onClick = { onSubmit(values, false) }, enabled = !saving) { Text(stringResource(R.string.dashboard_save)) }
},
dismissButton = {
Row {
TextButton(onClick = { onSubmit(values, true) }, enabled = !saving) { Text(stringResource(R.string.dashboard_memory_run_setup)) }
TextButton(onClick = onDismiss, enabled = !saving) { Text(stringResource(R.string.dashboard_cancel)) }
}
},
)
}
private fun qrBitmap(payload: String): Bitmap {
val matrix = QRCodeWriter().encode(payload, BarcodeFormat.QR_CODE, 640, 640)
val pixels = IntArray(matrix.width * matrix.height)
for (y in 0 until matrix.height) for (x in 0 until matrix.width) {
pixels[y * matrix.width + x] = if (matrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE
}
return Bitmap.createBitmap(pixels, matrix.width, matrix.height, Bitmap.Config.ARGB_8888)
}
private data class DashboardImportMetadata(val name: String, val length: Long?)
private fun dashboardImportMetadata(resolver: ContentResolver, uri: Uri): DashboardImportMetadata {
var name: String? = null
var length: Long? = null
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)
?.use { cursor ->
if (cursor.moveToFirst()) {
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
if (nameIndex >= 0 && !cursor.isNull(nameIndex)) name = cursor.getString(nameIndex)
if (sizeIndex >= 0 && !cursor.isNull(sizeIndex)) length = cursor.getLong(sizeIndex).takeIf { it >= 0 }
}
}
return DashboardImportMetadata(
name = name?.takeIf { it.isNotBlank() }
?: uri.lastPathSegment?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
?: "hermes-backup.zip",
length = length,
)
}
@Composable
private fun WhatsAppSetupDialog(
onboarding: WhatsAppOnboardingState?,
busy: Boolean,
onStart: (String, String) -> Unit,
onApply: (WhatsAppOnboardingState) -> Unit,
onDismiss: () -> Unit,
) {
var mode by remember { mutableStateOf("bot") }
var allowedUsers by remember { mutableStateOf("") }
val qr = remember(onboarding?.qrPayload) {
onboarding?.qrPayload?.let { runCatching { qrBitmap(it) }.getOrNull() }
}
AlertDialog(
onDismissRequest = { if (!busy) onDismiss() },
title = { Text(stringResource(R.string.dashboard_whatsapp_title)) },
text = {
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(10.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
if (onboarding == null) {
Text(stringResource(R.string.dashboard_whatsapp_help), style = MaterialTheme.typography.bodySmall)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = { mode = "bot" }) { Text(stringResource(R.string.dashboard_whatsapp_bot)) }
OutlinedButton(onClick = { mode = "self-chat" }) { Text(stringResource(R.string.dashboard_whatsapp_self_chat)) }
}
OutlinedTextField(
value = allowedUsers,
onValueChange = { allowedUsers = it },
label = { Text(stringResource(R.string.dashboard_whatsapp_allowed_users)) },
modifier = Modifier.fillMaxWidth(),
)
} else {
Text(onboarding.status.replace('_', ' ').uppercase(), style = MaterialTheme.typography.labelMedium)
qr?.let { Image(it.asImageBitmap(), contentDescription = stringResource(R.string.dashboard_whatsapp_qr), modifier = Modifier.size(280.dp)) }
onboarding.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
if (onboarding.status !in setOf("connected", "error", "expired")) {
Text(stringResource(R.string.dashboard_whatsapp_scan), style = MaterialTheme.typography.bodySmall)
}
}
}
},
confirmButton = {
if (onboarding == null) {
Button(onClick = { onStart(mode, allowedUsers) }, enabled = !busy) { Text(stringResource(R.string.dashboard_whatsapp_start)) }
} else if (onboarding.status == "connected") {
Button(onClick = { onApply(onboarding) }, enabled = !busy) { Text(stringResource(R.string.dashboard_whatsapp_apply)) }
}
},
dismissButton = { TextButton(onClick = onDismiss, enabled = !busy) { Text(stringResource(R.string.dashboard_cancel)) } },
)
}
@@ -64,6 +64,8 @@ import com.hermesandroid.relay.R
import com.hermesandroid.relay.auth.PairedDeviceInfo
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.hasSecureProxy
import com.hermesandroid.relay.data.secureLinkCoversAllServices
import com.hermesandroid.relay.data.routeAuthority
import com.hermesandroid.relay.ui.components.SessionTtlPickerDialog
import com.hermesandroid.relay.ui.components.TransportSecurityBadge
@@ -939,6 +941,17 @@ private fun EndpointsSubList(
fontFamily = FontFamily.Monospace,
modifier = Modifier.weight(1f),
)
if (candidate.hasSecureProxy()) {
Text(
text = if (candidate.secureLinkCoversAllServices()) {
stringResource(R.string.secure_link_pinned_tls_short)
} else {
stringResource(R.string.secure_link_partial_short)
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
if (isActive) {
Text(
text = stringResource(R.string.paired_devices_active),
@@ -77,10 +77,12 @@ import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.ProfileConfigResponse
import com.hermesandroid.relay.data.ProfileMemoryEntry
import com.hermesandroid.relay.data.ProfileSkillEntry
import com.hermesandroid.relay.data.GatewayProfileToolset
import com.hermesandroid.relay.ui.LocalSnackbarHost
import com.hermesandroid.relay.viewmodel.InspectorSection
import com.hermesandroid.relay.viewmodel.LoadState
import com.hermesandroid.relay.viewmodel.ProfileInspectorViewModel
import com.hermesandroid.relay.viewmodel.ProfileInspectorSource
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
@@ -123,6 +125,8 @@ fun ProfileInspectorScreen(
val soulState by viewModel.soulState.collectAsState()
val memoryState by viewModel.memoryState.collectAsState()
val skillsState by viewModel.skillsState.collectAsState()
val source by viewModel.source.collectAsState()
val gatewayDescription by viewModel.gatewayDescription.collectAsState()
// Lazy first-load on screen entry. Keyed on the profile name so a
// re-entry for a different profile (unlikely but possible via deep
@@ -244,6 +248,18 @@ fun ProfileInspectorScreen(
InspectorSection.Config -> ConfigPane(
state = configState,
onRetry = { viewModel.refreshSection(InspectorSection.Config) },
gatewayEditable = source == ProfileInspectorSource.Gateway,
editing = viewModel.configEditing.collectAsState().value,
descriptionDraft = viewModel.configDescriptionDraft.collectAsState().value,
providerDraft = viewModel.configProviderDraft.collectAsState().value,
modelDraft = viewModel.configModelDraft.collectAsState().value,
saving = viewModel.configSaving.collectAsState().value,
onBeginEdit = viewModel::beginConfigEdit,
onDescriptionChange = viewModel::updateConfigDescriptionDraft,
onProviderChange = viewModel::updateConfigProviderDraft,
onModelChange = viewModel::updateConfigModelDraft,
onSave = viewModel::saveConfigEdit,
onCancel = viewModel::cancelConfigEdit,
)
InspectorSection.Soul -> SoulPane(
state = soulState,
@@ -282,6 +298,13 @@ fun ProfileInspectorScreen(
onToggleSkill = { name, enabled ->
viewModel.toggleSkill(name, enabled)
},
gatewayNative = source == ProfileInspectorSource.Gateway,
skillDrafts = viewModel.skillDrafts.collectAsState().value,
toolsets = gatewayDescription?.toolsets.orEmpty(),
toolsetDrafts = viewModel.toolsetDrafts.collectAsState().value,
saving = viewModel.skillsSaving.collectAsState().value,
onToggleToolset = viewModel::toggleToolset,
onSaveDrafts = viewModel::saveSkillEdits,
)
}
}
@@ -291,6 +314,14 @@ fun ProfileInspectorScreen(
private data class InspectorTab(val label: String, val section: InspectorSection)
internal fun profileConfigSaveEnabled(provider: String, model: String, saving: Boolean): Boolean =
provider.isNotBlank() && model.isNotBlank() && !saving
internal fun gatewayDraftSaveVisible(
skillDrafts: Map<String, Boolean>,
toolsetDrafts: Map<String, Boolean>,
): Boolean = skillDrafts.isNotEmpty() || toolsetDrafts.isNotEmpty()
// ---------------------------------------------------------------
// Config pane — JSON tree with collapsible nested objects.
// ---------------------------------------------------------------
@@ -299,6 +330,18 @@ private data class InspectorTab(val label: String, val section: InspectorSection
private fun ConfigPane(
state: LoadState<ProfileConfigResponse>,
onRetry: () -> Unit,
gatewayEditable: Boolean,
editing: Boolean,
descriptionDraft: String,
providerDraft: String,
modelDraft: String,
saving: Boolean,
onBeginEdit: () -> Unit,
onDescriptionChange: (String) -> Unit,
onProviderChange: (String) -> Unit,
onModelChange: (String) -> Unit,
onSave: () -> Unit,
onCancel: () -> Unit,
) {
PaneShell(state = state, onRetry = onRetry) { response ->
var showRawConfig by remember(response.profile, response.config) {
@@ -318,6 +361,21 @@ private fun ConfigPane(
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
if (gatewayEditable) {
GatewayConfigEditor(
editing = editing,
description = descriptionDraft,
provider = providerDraft,
model = modelDraft,
saving = saving,
onBeginEdit = onBeginEdit,
onDescriptionChange = onDescriptionChange,
onProviderChange = onProviderChange,
onModelChange = onModelChange,
onSave = onSave,
onCancel = onCancel,
)
}
ConfigSummaryCard(response)
OutlinedButton(
@@ -363,6 +421,75 @@ private fun ConfigPane(
}
}
@Composable
private fun GatewayConfigEditor(
editing: Boolean,
description: String,
provider: String,
model: String,
saving: Boolean,
onBeginEdit: () -> Unit,
onDescriptionChange: (String) -> Unit,
onProviderChange: (String) -> Unit,
onModelChange: (String) -> Unit,
onSave: () -> Unit,
onCancel: () -> Unit,
) {
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer),
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier = Modifier.weight(1f)) {
Text(stringResource(R.string.profile_inspector_gateway_settings), fontWeight = FontWeight.SemiBold)
Text(
stringResource(R.string.profile_inspector_gateway_settings_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (!editing) {
IconButton(onClick = onBeginEdit) {
Icon(Icons.Filled.Edit, stringResource(R.string.profile_inspector_edit_config))
}
}
}
if (editing) {
OutlinedTextField(
value = description,
onValueChange = onDescriptionChange,
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.profile_inspector_description)) },
)
OutlinedTextField(
value = provider,
onValueChange = onProviderChange,
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text(stringResource(R.string.profile_inspector_provider)) },
)
OutlinedTextField(
value = model,
onValueChange = onModelChange,
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text(stringResource(R.string.profile_inspector_model)) },
)
EditorBottomBar(
saving = saving,
canSave = profileConfigSaveEnabled(provider, model, saving),
onSave = onSave,
onCancel = onCancel,
)
}
}
}
}
@Composable
private fun ConfigSummaryCard(response: ProfileConfigResponse) {
val topLevelCount = response.config.size
@@ -1334,9 +1461,16 @@ private fun SkillsPane(
onRetry: () -> Unit,
toggleSupported: Boolean?,
onToggleSkill: (String, Boolean) -> Unit,
gatewayNative: Boolean,
skillDrafts: Map<String, Boolean>,
toolsets: List<GatewayProfileToolset>,
toolsetDrafts: Map<String, Boolean>,
saving: Boolean,
onToggleToolset: (String, Boolean) -> Unit,
onSaveDrafts: () -> Unit,
) {
PaneShell(state = state, onRetry = onRetry) { response ->
if (response.skills.isEmpty()) {
if (response.skills.isEmpty() && !gatewayNative) {
Column(
modifier = Modifier
.fillMaxSize()
@@ -1391,6 +1525,30 @@ private fun SkillsPane(
visibleCount = visibleSkills.size,
)
}
if (gatewayNative && toolsets.isNotEmpty()) {
item(key = "__toolsets__") {
GatewayToolsetsCard(
toolsets = toolsets,
drafts = toolsetDrafts,
onToggle = onToggleToolset,
)
}
}
if (gatewayNative && gatewayDraftSaveVisible(skillDrafts, toolsetDrafts)) {
item(key = "__save_gateway_drafts__") {
Button(
onClick = onSaveDrafts,
enabled = !saving,
modifier = Modifier.fillMaxWidth(),
) {
if (saving) {
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(8.dp))
}
Text(stringResource(if (saving) R.string.profile_inspector_saving else R.string.profile_inspector_save_changes))
}
}
}
if (visibleSkills.isEmpty()) {
item(key = "__skills_empty_filter__") {
Card(
@@ -1430,6 +1588,8 @@ private fun SkillsPane(
},
toggleSupported = toggleSupported,
onToggleSkill = onToggleSkill,
gatewayNative = gatewayNative,
skillDrafts = skillDrafts,
)
}
if (toggleSupported == false) {
@@ -1562,6 +1722,8 @@ private fun SkillCategorySection(
onToggleExpanded: () -> Unit,
toggleSupported: Boolean?,
onToggleSkill: (String, Boolean) -> Unit,
gatewayNative: Boolean,
skillDrafts: Map<String, Boolean>,
) {
val categoryStateDescription = stringResource(
if (expanded) {
@@ -1622,6 +1784,7 @@ private fun SkillCategorySection(
skill = skill,
toggleSupported = toggleSupported,
onToggleSkill = onToggleSkill,
controlledEnabled = if (gatewayNative) skillDrafts[skill.name] ?: skill.enabled else null,
)
if (index != skills.lastIndex) {
HorizontalDivider(
@@ -1640,6 +1803,7 @@ private fun SkillRow(
skill: ProfileSkillEntry,
toggleSupported: Boolean?,
onToggleSkill: (String, Boolean) -> Unit,
controlledEnabled: Boolean?,
) {
// Optimistic local toggle state. The VM's emitted events revert us
// on failure; on success the next `/skills` refetch will overwrite
@@ -1652,6 +1816,7 @@ private fun SkillRow(
// null (probe hasn't completed) → leave tappable but the PUT will
// ask authoritatively.
val switchEnabled = toggleSupported != false
val displayedEnabled = controlledEnabled ?: localEnabled
Row(
modifier = Modifier
@@ -1666,7 +1831,7 @@ private fun SkillRow(
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
)
if (!localEnabled) {
if (!displayedEnabled) {
Spacer(modifier = Modifier.width(8.dp))
Text(
text = stringResource(R.string.profile_inspector_disabled),
@@ -1684,7 +1849,7 @@ private fun SkillRow(
}
}
val toggleDescription = stringResource(
if (localEnabled) {
if (displayedEnabled) {
R.string.profile_inspector_disable_skill
} else {
R.string.profile_inspector_enable_skill
@@ -1692,7 +1857,7 @@ private fun SkillRow(
skill.name,
)
androidx.compose.material3.Switch(
checked = localEnabled,
checked = displayedEnabled,
enabled = switchEnabled,
modifier = Modifier.semantics {
contentDescription = toggleDescription
@@ -1705,7 +1870,7 @@ private fun SkillRow(
// the next recomposition sees — when the VM updates
// the flag to false post-call, we reset the switch to
// the prior state on the next pass.
localEnabled = new
if (controlledEnabled == null) localEnabled = new
onToggleSkill(skill.name, new)
},
)
@@ -1720,6 +1885,44 @@ private fun SkillRow(
}
}
@Composable
private fun GatewayToolsetsCard(
toolsets: List<GatewayProfileToolset>,
drafts: Map<String, Boolean>,
onToggle: (String, Boolean) -> Unit,
) {
Card(modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(stringResource(R.string.profile_inspector_toolsets), fontWeight = FontWeight.SemiBold)
Text(
stringResource(R.string.profile_inspector_toolsets_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
toolsets.forEach { toolset ->
val enabled = drafts[toolset.name] ?: toolset.enabled
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
Text(toolset.name, style = MaterialTheme.typography.bodyMedium)
Text(
stringResource(R.string.profile_inspector_tool_count, toolset.toolCount),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
androidx.compose.material3.Switch(
checked = enabled,
onCheckedChange = { onToggle(toolset.name, it) },
)
}
}
}
}
}
// ---------------------------------------------------------------
// Shared UI bits
// ---------------------------------------------------------------
@@ -2442,7 +2442,12 @@ class ChatViewModel : ViewModel() {
* [regenerateFromMessage] and consumed by the next [startStream]
* gateway dispatch as `truncate_before_user_ordinal`.
*/
private var pendingTruncateOrdinal: Int? = null
private data class PendingGatewayTruncation(
val ordinal: Int,
val rowId: Long?,
)
private var pendingGatewayTruncation: PendingGatewayTruncation? = null
/**
* Provider for the active agent-profile pick — wired from [RelayApp] at
@@ -3225,7 +3230,7 @@ class ChatViewModel : ViewModel() {
selectedReasoningEffortConfirmedIdentity = null
_reasoningDisplay.value = null
_selectedPersonality.value = "default"
pendingTruncateOrdinal = null
pendingGatewayTruncation = null
chatHandler?.let { handler ->
handler.clearMessages()
handler.clearSessions()
@@ -3318,7 +3323,7 @@ class ChatViewModel : ViewModel() {
// recompute it now that the overlay is cleared so the header/bubbles read
// the new profile's base identity, not the old persona.
handler.activeAgentName = currentAgentDisplayName()
pendingTruncateOrdinal = null
pendingGatewayTruncation = null
handler.clearSessions()
handler.setSessionId(sessionId)
publishQueuedMessages()
@@ -4235,6 +4240,7 @@ class ChatViewModel : ViewModel() {
HermesCardInput.Kinds.CHOICE
},
choices = ask.choices.orEmpty(),
multiSelect = ask.multiSelect,
allowFreeText = true,
expiresAtMillis = expiresAt,
),
@@ -4500,7 +4506,7 @@ class ChatViewModel : ViewModel() {
.indexOfFirst { it.id == userMessageId }
if (ordinal < 0) return false
handler.truncateMessagesFrom(userMessageId)
pendingTruncateOrdinal = ordinal
pendingGatewayTruncation = PendingGatewayTruncation(ordinal, target.rowId)
sendMessageInternal(apiClient, handler, newText)
return true
}
@@ -4634,7 +4640,7 @@ class ChatViewModel : ViewModel() {
}
val summary = when (result.status.lowercase()) {
"aborted" -> "Compression aborted."
"noop", "no_op" -> "Nothing to compress."
"noop", "no_op" -> result.output ?: "Nothing to compress."
"legacy" -> result.output ?: "Compression command sent through legacy slash support."
else -> result.output ?: compressionSummary(result)
}
@@ -5041,6 +5047,7 @@ class ChatViewModel : ViewModel() {
requestId = ask.ask.requestId,
text = ask.ask.text,
choices = ask.ask.choices,
multiSelect = ask.ask.multiSelect,
smartDenied = ask.ask.smartDenied,
envVar = ask.ask.envVar,
timeoutSeconds = ask.ask.timeoutSeconds,
@@ -5225,6 +5232,7 @@ class ChatViewModel : ViewModel() {
requestId = saved.requestId,
text = saved.text,
choices = saved.choices,
multiSelect = saved.multiSelect,
smartDenied = saved.smartDenied,
envVar = saved.envVar,
timeoutSeconds = saved.timeoutSeconds,
@@ -7661,8 +7669,8 @@ class ChatViewModel : ViewModel() {
// Edit-and-regenerate ordinal — armed by regenerateFromMessage for
// exactly the next turn; consumed even when the turn lands on SSE
// (the post-turn reload reconciles divergence in that case).
val truncateOrdinal = pendingTruncateOrdinal
pendingTruncateOrdinal = null
val pendingTruncation = pendingGatewayTruncation
pendingGatewayTruncation = null
val gateway = gatewayClient
_steerableTurn.value = false
@@ -7826,8 +7834,10 @@ class ChatViewModel : ViewModel() {
),
attachments = attachments.orEmpty()
.map { it.toGatewayAttachment() },
truncateBeforeUserOrdinal = truncateOrdinal,
truncateBeforeUserOrdinal = pendingTruncation?.ordinal,
truncateBeforeRowId = pendingTruncation?.rowId,
queuedFollowUp = queuedFollowUp,
onSurvivorUserRowIds = handler::rebindSurvivorUserRowIds,
onPreflightFailure = {
_steerableTurn.value = false
if (intentionallyCancelled) {
@@ -33,6 +33,7 @@ import com.hermesandroid.relay.data.DemoMode
import com.hermesandroid.relay.data.DashboardEndpoint
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.hasSecureProxy
import com.hermesandroid.relay.R
import com.hermesandroid.relay.data.MediaSettingsRepository
import com.hermesandroid.relay.data.PairingPreferences
@@ -82,9 +83,14 @@ import com.hermesandroid.relay.network.upstream.mirrorDashboardSessionCookies
import com.hermesandroid.relay.network.upstream.DashboardAuthSession
import com.hermesandroid.relay.network.upstream.DashboardCookieStore
import com.hermesandroid.relay.network.upstream.DashboardStatus
import com.hermesandroid.relay.network.upstream.multiplexServedProfiles
import com.hermesandroid.relay.network.upstream.NativeDashboardAuthClient
import com.hermesandroid.relay.network.upstream.ToolsetInfo
import com.hermesandroid.relay.network.shared.EndpointResolver
import com.hermesandroid.relay.network.shared.buildPluginProxyClient
import com.hermesandroid.relay.network.shared.buildHermesReachClient
import com.hermesandroid.relay.network.shared.hermesReachRouteOrNull
import com.hermesandroid.relay.network.shared.pluginProxyRoutesOrNull
import com.hermesandroid.relay.network.upstream.GatewayAvailability
import com.hermesandroid.relay.network.upstream.ActiveTurnKeepAliveRegistry
import com.hermesandroid.relay.data.KEY_GATEWAY_KEEP_ALIVE
@@ -238,6 +244,7 @@ internal fun resolveEffectiveDashboardUrl(
endpoint: EndpointCandidate?,
): String {
if (connection == null) return ""
endpoint?.pluginProxyRoutesOrNull()?.dashboardBaseUrl?.let { return it }
endpoint?.dashboard?.url
?.takeIf { it.isNotBlank() }
?.let { return it }
@@ -260,6 +267,7 @@ internal fun resolveEffectiveApiServerUrl(
endpoint: EndpointCandidate?,
): String {
if (savedUrl.isBlank()) return ""
endpoint?.pluginProxyRoutesOrNull()?.apiBaseUrl?.let { return it }
return endpoint?.api?.url?.takeIf { it.isNotBlank() } ?: savedUrl
}
@@ -608,6 +616,25 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
private val endpointResolver = EndpointResolver(
httpClient = endpointProbeClient,
clientForCandidate = { candidate ->
candidate.pluginProxyRoutesOrNull()?.let { proxy ->
val tokenProvider = { (authManager.authState.value as? AuthState.Paired)?.token }
if (candidate.hermesReachRouteOrNull() != null) {
buildHermesReachClient(
baseBuilder = endpointProbeClient.newBuilder(),
outerClient = endpointProbeClient,
candidate = candidate,
sessionTokenProvider = tokenProvider,
)
} else {
buildPluginProxyClient(
baseBuilder = endpointProbeClient.newBuilder(),
routes = proxy,
sessionTokenProvider = tokenProvider,
)
}
}
},
context = application,
)
@@ -618,6 +645,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
context = application,
endpointResolver = endpointResolver,
endpointCandidatesProvider = { activeRouteCandidatesSnapshot() },
proxyClientProvider = { url -> pluginProxyClientForUrl(url) },
// Pull the active device id through AuthManager — it's the same id
// PairingPreferences keys the endpoint list on. Nullable wrapper
// because AuthManager.getOrCreateDeviceId() is suspending.
@@ -713,6 +741,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
tokenStoreKeyProvider = { cid ->
connectionStore.connections.value.firstOrNull { it.id == cid }?.tokenStoreKey
},
pinnedClientProvider = { url, base ->
pluginProxyClientForUrl(url, base, includeRelaySessionHeader = false)
},
)
// Agent-profiles collaborator — owns the merged profile list, the
@@ -784,7 +815,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
*/
val relayRowState: StateFlow<RelayRowState> = combine(
_relayUiState,
connectionManager.activeEndpoint,
connectionManager.activeRelayEndpoint,
) { phase, endpoint ->
RelayRowState(phase = phase, activeEndpointRole = endpoint?.role)
}.stateIn(
@@ -862,11 +893,55 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
private fun effectiveApiServerUrlSnapshot(): String =
resolveEffectiveApiServerUrl(
savedUrl = _apiServerUrl.value,
endpoint = connectionManager.activeEndpoint.value,
endpoint = connectionManager.activeApiEndpoint.value,
)
private fun effectiveRelayUrlSnapshot(): String =
connectionManager.activeEndpoint.value?.relay?.url ?: autoRelayUrlSnapshot()
connectionManager.activeEndpoint.value?.relay?.url
?: autoRelayUrlSnapshot()
private fun effectiveRelayWebSocketUrlSnapshot(): String =
connectionManager.activeRelayEndpoint.value?.pluginProxyRoutesOrNull()?.relayWebSocketUrl
?: connectionManager.activeRelayEndpoint.value?.relay?.url
?: autoRelayUrlSnapshot()
private fun pluginProxyClientForUrl(
url: String,
baseClient: OkHttpClient? = null,
includeRelaySessionHeader: Boolean = true,
): OkHttpClient? {
val requestAuthority = runCatching {
val parsed = java.net.URI(url)
val port = if (parsed.port > 0) parsed.port else 443
"${parsed.host?.lowercase()}:$port"
}.getOrNull() ?: return null
val candidate = activeConnection.value?.routeCandidates.orEmpty()
.firstOrNull { it.pluginProxyRoutesOrNull()?.authority == requestAuthority }
?: return null
val routes = candidate.pluginProxyRoutesOrNull() ?: return null
val configuredBuilder = (baseClient?.newBuilder() ?: OkHttpClient.Builder())
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(0, TimeUnit.MILLISECONDS)
.pingInterval(30, TimeUnit.SECONDS)
val sessionTokenProvider = {
(authManager.authState.value as? AuthState.Paired)?.token
}
if (candidate.hermesReachRouteOrNull() != null) {
return buildHermesReachClient(
baseBuilder = configuredBuilder,
outerClient = endpointProbeClient,
candidate = candidate,
sessionTokenProvider = sessionTokenProvider,
includeRelaySessionHeader = includeRelaySessionHeader,
)
}
return buildPluginProxyClient(
baseBuilder = configuredBuilder,
routes = routes,
sessionTokenProvider = sessionTokenProvider,
includeRelaySessionHeader = includeRelaySessionHeader,
)
}
private fun autoRelayUrlSnapshot(): String {
val savedRelay = _relayUrl.value
@@ -1127,7 +1202,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
*/
val effectiveApiServerUrl: StateFlow<String> = combine(
_apiServerUrl,
connectionManager.activeEndpoint,
connectionManager.activeApiEndpoint,
) { savedUrl, endpoint ->
resolveEffectiveApiServerUrl(savedUrl, endpoint)
}.stateIn(viewModelScope, SharingStarted.Eagerly, "")
@@ -1857,6 +1932,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
}
init {
authManager.setActiveEndpointProvider { connectionManager.activeRelayEndpoint.value }
// Materialize the independent central and floating preferences. Legacy
// users retain the prior visual in both roles until they choose otherwise.
viewModelScope.launch {
@@ -2461,6 +2537,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
}
private fun installAuthManager(am: AuthManager) {
am.setActiveEndpointProvider { connectionManager.activeRelayEndpoint.value }
authManager = am
// Push into the flow so the flatMapLatest chains on authState /
// pairingCode / currentPairedSession repoint to the new manager.
@@ -4559,14 +4636,14 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
?.dashboardLastStatus
val liveTopology = topologyConnectionId == activeConnectionId
val mode = if (liveTopology) topologyGatewayMode else persisted?.gatewayMode
val profiles = if (liveTopology) topologyProfiles else persisted?.profiles.orEmpty()
val profiles = if (liveTopology) topologyProfiles else persisted?.servedProfiles.orEmpty()
return mode.equals("multiplex", ignoreCase = true) && profile.name in profiles
}
/** Keep chat routing synchronized with the latest public dashboard topology. */
private suspend fun updateDashboardTopology(connectionId: String, status: DashboardStatus?) {
val nextMode = status?.gatewayMode
val nextProfiles = status?.profiles.orEmpty()
val nextProfiles = status?.multiplexServedProfiles().orEmpty()
val changed = topologyConnectionId != connectionId ||
topologyGatewayMode != nextMode ||
topologyProfiles != nextProfiles
@@ -4611,6 +4688,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
previous.authRequired == status?.authRequired &&
previous.authenticated == session?.authenticated &&
previous.gatewayMode == status?.gatewayMode &&
previous.servedProfiles == status?.multiplexServedProfiles().orEmpty() &&
previous.profiles == status?.profiles.orEmpty()
if (!materiallySame) {
recordDashboardStatus(status = status, session = session, reachable = reachable)
@@ -5177,6 +5255,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
gatewayTicketAvailable = gatewayTicketAvailable,
message = message,
gatewayMode = status?.gatewayMode,
servedProfiles = status?.multiplexServedProfiles().orEmpty(),
profiles = status?.profiles.orEmpty(),
),
)
@@ -5211,6 +5290,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
gatewayTicketAvailable = false,
message = "Dashboard session cleared",
gatewayMode = active?.dashboardLastStatus?.gatewayMode,
servedProfiles = active?.dashboardLastStatus?.servedProfiles.orEmpty(),
profiles = active?.dashboardLastStatus?.profiles.orEmpty(),
),
)
@@ -5617,7 +5697,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
profileApiUrl = selectedProfile?.apiServerUrl,
selectedProfileName = selectedProfile?.name,
gatewayMode = if (liveTopology) topologyGatewayMode else topology?.gatewayMode,
servedProfiles = if (liveTopology) topologyProfiles else topology?.profiles.orEmpty(),
servedProfiles = if (liveTopology) topologyProfiles else topology?.servedProfiles.orEmpty(),
)
}
@@ -5742,7 +5822,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
// a coherent in-flight pose instead of flashing the previous
// result through.
_apiServerHealth.value = HealthStatus.Probing
val client = HermesApiClient(baseUrl = url, apiKey = key)
val client = HermesApiClient(
baseUrl = url,
apiKey = key,
httpClient = pluginProxyClientForUrl(
url, includeRelaySessionHeader = false
),
)
_apiClient.value = client
shutdownClientOffMain(oldClient)
val ok = client.checkHealth()
@@ -5774,7 +5860,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
?.dashboardLastStatus
val liveTopology = topologyConnectionId == activeConnectionId
val gatewayMode = if (liveTopology) topologyGatewayMode else topology?.gatewayMode
val servedProfiles = if (liveTopology) topologyProfiles else topology?.profiles.orEmpty()
val servedProfiles = if (liveTopology) topologyProfiles else topology?.servedProfiles.orEmpty()
val usesMultiplexProfileKey = ProfileApiUrlResolver.usesMultiplexProfileKey(
profileApiUrl = selectedProfile?.apiServerUrl,
selectedProfileName = selectedProfile?.name,
@@ -5821,7 +5907,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
return
}
val nextProfileClient = HermesApiClient(baseUrl = profileApiUrl, apiKey = key)
val nextProfileClient = HermesApiClient(
baseUrl = profileApiUrl,
apiKey = key,
httpClient = pluginProxyClientForUrl(
profileApiUrl, includeRelaySessionHeader = false
),
)
profileChatApiClient = nextProfileClient
profileChatApiClientUrl = profileApiUrl
profileChatApiClientKey = key
@@ -5870,7 +5962,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
}
fun connectRelay() {
connectRelayInternal(effectiveRelayUrlSnapshot())
connectRelayInternal(effectiveRelayWebSocketUrlSnapshot())
}
/**
@@ -6273,6 +6365,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
* is unavailable.
*/
suspend fun lookupEndpointPin(candidate: com.hermesandroid.relay.data.EndpointCandidate): String? {
candidate.proxy?.pinSha256?.takeIf { candidate.hasSecureProxy() }?.let { return it }
val hostPort = candidate.routeAuthority() ?: return null
val pins = PairingPreferences.getTofuPins(getApplication())
return pins[hostPort]
@@ -3,11 +3,21 @@ package com.hermesandroid.relay.viewmodel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hermesandroid.relay.data.GatewayProfileConfigureResult
import com.hermesandroid.relay.data.GatewayProfileDescription
import com.hermesandroid.relay.data.GatewayProfileEditorClient
import com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException
import com.hermesandroid.relay.data.GatewayProfilePatch
import com.hermesandroid.relay.data.GatewayProfileSection
import com.hermesandroid.relay.data.LegacyProfileInspectorClient
import com.hermesandroid.relay.data.ProfileConfigResponse
import com.hermesandroid.relay.data.ProfileMemoryResponse
import com.hermesandroid.relay.data.ProfileSkillEntry
import com.hermesandroid.relay.data.ProfileSkillsResponse
import com.hermesandroid.relay.data.ProfileSoulResponse
import com.hermesandroid.relay.network.relay.RelayProfileInspectorClient
import com.hermesandroid.relay.data.RelaySkillToggleResult
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
@@ -15,24 +25,12 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
/**
* One of the four sections the inspector screen can display — used by
* [ProfileInspectorViewModel.refreshSection] to target a single pane
* without reloading the whole screen.
*/
enum class InspectorSection { Config, Soul, Memory, Skills }
/**
* Generic load state for each of the four inspector sections. Kept
* separate per section so a slow `/memory` fetch doesn't block the
* already-arrived `/config` tab from rendering.
*
* `Idle` is the pre-first-fetch state (useful for "don't render anything
* yet"); `Loading` is during an active fetch; `Loaded` carries the
* successfully-parsed payload; `Error` carries a human-readable message
* for inline display with a retry button.
*/
sealed class LoadState<out T> {
data object Idle : LoadState<Nothing>()
data object Loading : LoadState<Nothing>()
@@ -40,168 +38,150 @@ sealed class LoadState<out T> {
data class Error(val message: String) : LoadState<Nothing>()
}
enum class ProfileInspectorSource { Unknown, Gateway, Relay }
/**
* ViewModel for the Profile Inspector screen. Owns four load states
* (one per section) plus a one-shot `loadAll()` and per-section
* `refreshSection()` for pull-to-refresh. Lazy: no fetch is kicked off
* until the screen first calls [loadAll].
*
* The inspected profile name comes in via [SavedStateHandle] so it
* survives process death — Android nav graph arg → SavedStateHandle is
* the standard path. If the arg is missing (unexpected), [profileName]
* falls back to an empty string and every fetch short-circuits to an
* error state.
* Owns one immutable profile-name namespace. Gateway-native describe/configure
* is preferred when the active connection exposes it; Relay reads remain the
* compatibility fallback and the sole owner of memory-file editing.
*/
class ProfileInspectorViewModel(
private val client: RelayProfileInspectorClient,
private val legacyClient: LegacyProfileInspectorClient,
private val gatewayClient: GatewayProfileEditorClient?,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
/**
* Key the screen pass on. Read from [SavedStateHandle] so a
* process-death restore brings the same profile back — Android
* nav args are automatically mirrored into savedStateHandle when
* the screen is registered via `composable(route, arguments=...)`.
*/
val profileName: String =
savedStateHandle.get<String>(ARG_PROFILE_NAME).orEmpty()
val profileName: String = savedStateHandle.get<String>(ARG_PROFILE_NAME).orEmpty()
private val _configState =
MutableStateFlow<LoadState<ProfileConfigResponse>>(LoadState.Idle)
val configState: StateFlow<LoadState<ProfileConfigResponse>> =
_configState.asStateFlow()
private val _source = MutableStateFlow(ProfileInspectorSource.Unknown)
val source: StateFlow<ProfileInspectorSource> = _source.asStateFlow()
private val _soulState =
MutableStateFlow<LoadState<ProfileSoulResponse>>(LoadState.Idle)
val soulState: StateFlow<LoadState<ProfileSoulResponse>> =
_soulState.asStateFlow()
private val _gatewayDescription = MutableStateFlow<GatewayProfileDescription?>(null)
val gatewayDescription: StateFlow<GatewayProfileDescription?> = _gatewayDescription.asStateFlow()
private val _memoryState =
MutableStateFlow<LoadState<ProfileMemoryResponse>>(LoadState.Idle)
val memoryState: StateFlow<LoadState<ProfileMemoryResponse>> =
_memoryState.asStateFlow()
private val _configState = MutableStateFlow<LoadState<ProfileConfigResponse>>(LoadState.Idle)
val configState: StateFlow<LoadState<ProfileConfigResponse>> = _configState.asStateFlow()
private val _soulState = MutableStateFlow<LoadState<ProfileSoulResponse>>(LoadState.Idle)
val soulState: StateFlow<LoadState<ProfileSoulResponse>> = _soulState.asStateFlow()
private val _memoryState = MutableStateFlow<LoadState<ProfileMemoryResponse>>(LoadState.Idle)
val memoryState: StateFlow<LoadState<ProfileMemoryResponse>> = _memoryState.asStateFlow()
private val _skillsState = MutableStateFlow<LoadState<ProfileSkillsResponse>>(LoadState.Idle)
val skillsState: StateFlow<LoadState<ProfileSkillsResponse>> = _skillsState.asStateFlow()
private val _skillsState =
MutableStateFlow<LoadState<ProfileSkillsResponse>>(LoadState.Idle)
val skillsState: StateFlow<LoadState<ProfileSkillsResponse>> =
_skillsState.asStateFlow()
// -----------------------------------------------------------------
// UI view-state flags — session-scoped (no DataStore). All of these
// are kept on the VM rather than inside the Composable so they
// survive process-death restore via SavedStateHandle plumbing and
// — more importantly — recomposition-bound state hoists cleanly
// into a single source of truth per pane.
// -----------------------------------------------------------------
/**
* SOUL pane render mode. Defaults to rendered markdown — raw source
* is an explicit opt-in toggle in the top-right of the pane. Kept
* session-scoped because "Bailey wants raw this time" is a transient
* preference, not something worth persisting across app restarts.
*/
private val _soulRawView = MutableStateFlow(false)
val soulRawView: StateFlow<Boolean> = _soulRawView.asStateFlow()
fun toggleSoulRawView() {
_soulRawView.value = !_soulRawView.value
}
// -----------------------------------------------------------------
// Edit-mode state for SOUL + memory panes.
//
// Both panes share the same edit-mode pattern:
// 1. User taps the pencil icon → enters edit mode.
// 2. A monospace BasicTextField lets them type; state is kept in
// [soulDraft] / [memoryDraft]. The currently-saving flag is
// [soulSaving] / [memorySaving] so the Save button disables
// and a progress indicator renders.
// 3. On Save we PUT and, on success, reload the pane (fresh
// content from disk) and emit an [EditEvent.Saved] so the
// screen shows a snackbar. On failure we stay in edit mode so
// the user can retry.
//
// Per-memory-entry edit uses the same triple of flows keyed by
// filename. A separate key-based design (rather than "one memory
// entry at a time") keeps the door open to tabbed edits later
// without rewiring the state model.
// -----------------------------------------------------------------
/** User-facing snackbar events emitted by the edit pipeline. */
sealed class EditEvent {
data class Saved(val message: String) : EditEvent()
data class Error(val message: String) : EditEvent()
}
private val _editEvents = MutableSharedFlow<EditEvent>(
extraBufferCapacity = 8,
)
private val _editEvents = MutableSharedFlow<EditEvent>(extraBufferCapacity = 8)
val editEvents: SharedFlow<EditEvent> = _editEvents.asSharedFlow()
// --- SOUL edit state ---------------------------------------------
private val _soulRawView = MutableStateFlow(false)
val soulRawView: StateFlow<Boolean> = _soulRawView.asStateFlow()
fun toggleSoulRawView() { _soulRawView.value = !_soulRawView.value }
private val _configEditing = MutableStateFlow(false)
val configEditing: StateFlow<Boolean> = _configEditing.asStateFlow()
private val _configDescriptionDraft = MutableStateFlow("")
val configDescriptionDraft: StateFlow<String> = _configDescriptionDraft.asStateFlow()
private val _configProviderDraft = MutableStateFlow("")
val configProviderDraft: StateFlow<String> = _configProviderDraft.asStateFlow()
private val _configModelDraft = MutableStateFlow("")
val configModelDraft: StateFlow<String> = _configModelDraft.asStateFlow()
private val _configSaving = MutableStateFlow(false)
val configSaving: StateFlow<Boolean> = _configSaving.asStateFlow()
fun beginConfigEdit() {
val description = _gatewayDescription.value ?: return
_configDescriptionDraft.value = description.description
_configProviderDraft.value = description.provider
_configModelDraft.value = description.model
_configEditing.value = true
}
fun updateConfigDescriptionDraft(value: String) { _configDescriptionDraft.value = value }
fun updateConfigProviderDraft(value: String) { _configProviderDraft.value = value }
fun updateConfigModelDraft(value: String) { _configModelDraft.value = value }
fun cancelConfigEdit() { _configEditing.value = false }
fun saveConfigEdit() {
val baseline = _gatewayDescription.value ?: return
if (_configSaving.value) return
val descriptionChanged = _configDescriptionDraft.value != baseline.description
val modelChanged = _configProviderDraft.value != baseline.provider ||
_configModelDraft.value != baseline.model
if (modelChanged && (_configProviderDraft.value.isBlank() || _configModelDraft.value.isBlank())) {
_editEvents.tryEmit(EditEvent.Error("Provider and model are both required"))
return
}
val patch = GatewayProfilePatch(
description = _configDescriptionDraft.value.takeIf { descriptionChanged },
provider = _configProviderDraft.value.takeIf { modelChanged },
model = _configModelDraft.value.takeIf { modelChanged },
)
if (patch.requestedSections.isEmpty()) {
_configEditing.value = false
return
}
_configSaving.value = true
saveGatewayPatch(patch) { result, refreshed ->
if (GatewayProfileSection.Description in result.applied) {
_configDescriptionDraft.value = refreshed.description
}
if (GatewayProfileSection.Model in result.applied) {
_configProviderDraft.value = refreshed.provider
_configModelDraft.value = refreshed.model
}
_configEditing.value = result.failed.isNotEmpty()
_configSaving.value = false
}
}
private val _soulEditing = MutableStateFlow(false)
val soulEditing: StateFlow<Boolean> = _soulEditing.asStateFlow()
private val _soulDraft = MutableStateFlow("")
val soulDraft: StateFlow<String> = _soulDraft.asStateFlow()
private val _soulSaving = MutableStateFlow(false)
val soulSaving: StateFlow<Boolean> = _soulSaving.asStateFlow()
fun beginSoulEdit() {
val current = (soulState.value as? LoadState.Loaded)?.value?.content ?: ""
_soulDraft.value = current
_soulDraft.value = (soulState.value as? LoadState.Loaded)?.value?.content.orEmpty()
_soulEditing.value = true
}
fun updateSoulDraft(content: String) {
_soulDraft.value = content
}
fun cancelSoulEdit() {
_soulEditing.value = false
_soulDraft.value = ""
}
fun updateSoulDraft(content: String) { _soulDraft.value = content }
fun cancelSoulEdit() { _soulEditing.value = false }
fun saveSoulEdit() {
if (profileName.isBlank() || _soulSaving.value) return
val content = _soulDraft.value
_soulSaving.value = true
if (_source.value == ProfileInspectorSource.Gateway) {
saveGatewayPatch(GatewayProfilePatch(soul = _soulDraft.value)) { result, refreshed ->
if (GatewayProfileSection.Soul in result.applied) {
_soulDraft.value = refreshed.soul
_soulEditing.value = false
}
_soulSaving.value = false
}
return
}
viewModelScope.launch {
val result = client.updateSoul(profileName, content)
val result = legacyClient.updateSoul(profileName, _soulDraft.value)
_soulSaving.value = false
result.fold(
onSuccess = {
_soulEditing.value = false
_soulDraft.value = ""
_editEvents.tryEmit(EditEvent.Saved("SOUL saved"))
// Re-fetch the pane so the user sees freshly-loaded
// content (byte counts, truncation flags etc.).
refreshSection(InspectorSection.Soul)
},
onFailure = { err ->
_editEvents.tryEmit(
EditEvent.Error(err.message ?: "Save failed")
)
refreshLegacySection(InspectorSection.Soul)
},
onFailure = { _editEvents.tryEmit(EditEvent.Error(it.message ?: "Save failed")) },
)
}
}
// --- Memory edit state (keyed by filename) ------------------------
/**
* Filename of the memory entry currently being edited, or `null`
* when no memory entry is in edit mode. A single active edit at a
* time — matches the card-expansion model already in the pane.
*/
private val _memoryEditingFilename = MutableStateFlow<String?>(null)
val memoryEditingFilename: StateFlow<String?> = _memoryEditingFilename.asStateFlow()
private val _memoryDraft = MutableStateFlow("")
val memoryDraft: StateFlow<String> = _memoryDraft.asStateFlow()
private val _memorySaving = MutableStateFlow(false)
val memorySaving: StateFlow<Boolean> = _memorySaving.asStateFlow()
@@ -209,206 +189,290 @@ class ProfileInspectorViewModel(
_memoryEditingFilename.value = filename
_memoryDraft.value = initialContent
}
fun updateMemoryDraft(content: String) {
_memoryDraft.value = content
}
fun cancelMemoryEdit() {
_memoryEditingFilename.value = null
_memoryDraft.value = ""
}
fun updateMemoryDraft(content: String) { _memoryDraft.value = content }
fun cancelMemoryEdit() { _memoryEditingFilename.value = null }
fun saveMemoryEdit() {
val filename = _memoryEditingFilename.value ?: return
if (profileName.isBlank() || _memorySaving.value) return
val content = _memoryDraft.value
// Client-side filename sanity so we don't round-trip an obvious
// bad name and eat a 400. Server validates authoritatively.
val err = validateMemoryFilename(filename)
if (err != null) {
_editEvents.tryEmit(EditEvent.Error(err))
validateMemoryFilename(filename)?.let {
_editEvents.tryEmit(EditEvent.Error(it))
return
}
_memorySaving.value = true
viewModelScope.launch {
val result = client.updateMemoryEntry(profileName, filename, content)
val result = legacyClient.updateMemoryEntry(profileName, filename, _memoryDraft.value)
_memorySaving.value = false
result.fold(
onSuccess = {
_memoryEditingFilename.value = null
_memoryDraft.value = ""
_editEvents.tryEmit(EditEvent.Saved("Memory entry saved"))
refreshSection(InspectorSection.Memory)
},
onFailure = { e ->
_editEvents.tryEmit(
EditEvent.Error(e.message ?: "Save failed")
)
refreshLegacySection(InspectorSection.Memory)
},
onFailure = { _editEvents.tryEmit(EditEvent.Error(it.message ?: "Save failed")) },
)
}
}
// -----------------------------------------------------------------
// Skill toggle — server stubs this out as HTTP 501 today. We expose
// the probe result so the Skills pane can disable the Switch until
// the relay implements the endpoint, and we emit the 501 response
// as an EditEvent.Error on optimistic tap so the UI can revert
// the Switch visual state.
// -----------------------------------------------------------------
/**
* Capability flag. `null` = probe hasn't run yet (Switch renders
* enabled-but-pending); `true` = server claimed support on the
* capability probe; `false` = 501 / 404 / 405 — definitively not
* supported, Switch renders ghosted.
*/
private val _skillToggleSupported = MutableStateFlow<Boolean?>(null)
val skillToggleSupported: StateFlow<Boolean?> = _skillToggleSupported.asStateFlow()
private val _skillDrafts = MutableStateFlow<Map<String, Boolean>>(emptyMap())
val skillDrafts: StateFlow<Map<String, Boolean>> = _skillDrafts.asStateFlow()
private val _toolsetDrafts = MutableStateFlow<Map<String, Boolean>>(emptyMap())
val toolsetDrafts: StateFlow<Map<String, Boolean>> = _toolsetDrafts.asStateFlow()
private val _skillsSaving = MutableStateFlow(false)
val skillsSaving: StateFlow<Boolean> = _skillsSaving.asStateFlow()
/**
* One-shot capability probe. Fires at screen-open time from the
* Composable; idempotent — extra calls during the screen's lifetime
* reprobe but leave a positive result in place on failure.
*/
fun probeSkillToggleSupport() {
if (_source.value == ProfileInspectorSource.Gateway) {
_skillToggleSupported.value = true
return
}
viewModelScope.launch {
val supported = client.probeSkillToggleSupported()
_skillToggleSupported.value = supported
val supported = legacyClient.probeSkillToggleSupported()
if (_source.value != ProfileInspectorSource.Gateway) {
_skillToggleSupported.value = supported
}
}
}
/**
* Optimistic toggle — UI flips the switch immediately, then we PUT.
* On a 501 we emit an error event so the screen can revert the
* local visual state and cache "not supported" so subsequent taps
* are short-circuited.
*/
fun toggleSkill(skillName: String, enabled: Boolean) {
if (_source.value == ProfileInspectorSource.Gateway) {
val baseline = _gatewayDescription.value?.skills?.firstOrNull { it.name == skillName }
?.enabled ?: return
_skillDrafts.value = _skillDrafts.value.toMutableMap().apply {
if (enabled == baseline) remove(skillName) else put(skillName, enabled)
}
return
}
viewModelScope.launch {
val result = client.updateSkillToggle(skillName, enabled)
result.fold(
onSuccess = { outcome ->
when (outcome) {
is RelayProfileInspectorClient.SkillToggleResult.Ok ->
_editEvents.tryEmit(
EditEvent.Saved(
if (enabled) "Enabled $skillName" else "Disabled $skillName"
)
)
is RelayProfileInspectorClient.SkillToggleResult.NotImplemented -> {
legacyClient.updateSkillToggle(skillName, enabled).fold(
onSuccess = {
when (it) {
RelaySkillToggleResult.Ok -> {
_editEvents.tryEmit(EditEvent.Saved(if (enabled) "Enabled $skillName" else "Disabled $skillName"))
refreshLegacySection(InspectorSection.Skills)
}
RelaySkillToggleResult.NotImplemented -> {
_skillToggleSupported.value = false
_editEvents.tryEmit(
EditEvent.Error("Skill toggle not yet supported on this server")
)
_editEvents.tryEmit(EditEvent.Error("Skill toggle not yet supported on this server"))
}
}
},
onFailure = { err ->
_editEvents.tryEmit(
EditEvent.Error(err.message ?: "Skill toggle failed")
)
},
onFailure = { _editEvents.tryEmit(EditEvent.Error(it.message ?: "Skill toggle failed")) },
)
}
}
/**
* Local filename sanity for new/updated memory entries. Mirrors
* the rules the server worker enforces:
* - Must end in `.md`.
* - No path-traversal components (`..`).
* - No slashes/backslashes.
* - No leading `.` (dotfiles).
*
* Returns the error string to show, or null when the name passes.
* Running this client-side saves a server round-trip for the
* common typo cases and produces a tighter error ("filename must
* end in .md") than the server's generic 400.
*/
fun toggleToolset(toolsetName: String, enabled: Boolean) {
val baseline = _gatewayDescription.value?.toolsets?.firstOrNull { it.name == toolsetName }
?.enabled ?: return
_toolsetDrafts.value = _toolsetDrafts.value.toMutableMap().apply {
if (enabled == baseline) remove(toolsetName) else put(toolsetName, enabled)
}
}
fun saveSkillEdits() {
val description = _gatewayDescription.value ?: return
if (_source.value != ProfileInspectorSource.Gateway || _skillsSaving.value) return
val skillDrafts = _skillDrafts.value
val toolsetDrafts = _toolsetDrafts.value
val disabledSkills = if (skillDrafts.isNotEmpty()) {
description.skills.filter { !(skillDrafts[it.name] ?: it.enabled) }.map { it.name }
} else null
val enabledToolsets = if (toolsetDrafts.isNotEmpty()) {
description.toolsets.filter { toolsetDrafts[it.name] ?: it.enabled }.map { it.name }
.takeUnless { it.size == description.toolsets.size } ?: emptyList()
} else null
val patch = GatewayProfilePatch(
disabledSkills = disabledSkills,
enabledToolsets = enabledToolsets,
)
if (patch.requestedSections.isEmpty()) return
_skillsSaving.value = true
saveGatewayPatch(patch) { result, _ ->
if (GatewayProfileSection.Skills in result.applied) _skillDrafts.value = emptyMap()
if (GatewayProfileSection.Toolsets in result.applied) _toolsetDrafts.value = emptyMap()
_skillsSaving.value = false
}
}
fun validateMemoryFilename(name: String): String? {
val trimmed = name.trim()
if (trimmed.isEmpty()) return "Filename required"
if (!trimmed.endsWith(".md", ignoreCase = false)) {
return "Filename must end in .md"
}
if (!trimmed.endsWith(".md")) return "Filename must end in .md"
if (trimmed.startsWith(".")) return "Filename cannot start with '.'"
if (trimmed.contains("/") || trimmed.contains("\\")) {
return "Filename cannot contain slashes"
}
if (trimmed.contains("/") || trimmed.contains("\\")) return "Filename cannot contain slashes"
if (trimmed.contains("..")) return "Filename cannot contain '..'"
return null
}
/**
* Kick off all four fetches in parallel. Safe to call more than once
* — re-invoking replaces the load state from scratch (reverts any
* previous Error to Loading and re-tries).
*/
fun loadAll() {
if (profileName.isBlank()) {
val msg = "No profile name supplied"
_configState.value = LoadState.Error(msg)
_soulState.value = LoadState.Error(msg)
_memoryState.value = LoadState.Error(msg)
_skillsState.value = LoadState.Error(msg)
val error = LoadState.Error("No profile name supplied")
_configState.value = error
_soulState.value = error
_memoryState.value = error
_skillsState.value = error
return
}
refreshSection(InspectorSection.Config)
refreshSection(InspectorSection.Soul)
refreshSection(InspectorSection.Memory)
refreshSection(InspectorSection.Skills)
refreshEditorSections()
refreshLegacySection(InspectorSection.Memory)
}
/**
* Refresh a single section (pull-to-refresh on one pane). Transitions
* state to [LoadState.Loading] immediately so the UI can show a
* progress indicator; then fires the coroutine and updates the state
* with either [LoadState.Loaded] or [LoadState.Error].
*/
fun refreshSection(section: InspectorSection) {
if (profileName.isBlank()) return
if (section == InspectorSection.Memory) refreshLegacySection(section) else refreshEditorSections()
}
private fun refreshEditorSections() {
_configState.value = LoadState.Loading
_soulState.value = LoadState.Loading
_skillsState.value = LoadState.Loading
viewModelScope.launch {
val gatewayResult = gatewayClient?.describeProfile(profileName)
val gatewayDescription = gatewayResult?.getOrNull()
if (gatewayDescription != null) {
_source.value = ProfileInspectorSource.Gateway
applyGatewayDescription(gatewayDescription)
return@launch
}
loadLegacyEditorSections(gatewayResult?.exceptionOrNull())
}
}
private suspend fun loadLegacyEditorSections(gatewayError: Throwable?) = coroutineScope {
val config = async { legacyClient.fetchConfig(profileName) }
val soul = async { legacyClient.fetchSoul(profileName) }
val skills = async { legacyClient.fetchSkills(profileName) }
val configResult = config.await()
val soulResult = soul.await()
val skillsResult = skills.await()
if (configResult.isSuccess || soulResult.isSuccess || skillsResult.isSuccess) {
_source.value = ProfileInspectorSource.Relay
_gatewayDescription.value = null
}
val fallbackMessage = gatewayError
?.takeUnless { it is GatewayProfileEditorUnsupportedException }
?.message
_configState.value = configResult.toLoadState(fallbackMessage)
_soulState.value = soulResult.toLoadState(fallbackMessage)
_skillsState.value = skillsResult.toLoadState(fallbackMessage)
}
private fun refreshLegacySection(section: InspectorSection) {
when (section) {
InspectorSection.Config -> {
_configState.value = LoadState.Loading
viewModelScope.launch {
val result = client.fetchConfig(profileName)
_configState.value = result.toLoadState()
}
}
InspectorSection.Soul -> {
_soulState.value = LoadState.Loading
viewModelScope.launch {
val result = client.fetchSoul(profileName)
_soulState.value = result.toLoadState()
}
}
InspectorSection.Config, InspectorSection.Soul, InspectorSection.Skills -> refreshEditorSections()
InspectorSection.Memory -> {
_memoryState.value = LoadState.Loading
viewModelScope.launch {
val result = client.fetchMemory(profileName)
_memoryState.value = result.toLoadState()
}
}
InspectorSection.Skills -> {
_skillsState.value = LoadState.Loading
viewModelScope.launch {
val result = client.fetchSkills(profileName)
_skillsState.value = result.toLoadState()
_memoryState.value = legacyClient.fetchMemory(profileName).toLoadState()
}
}
}
}
private fun <T> Result<T>.toLoadState(): LoadState<T> = fold(
private fun applyGatewayDescription(description: GatewayProfileDescription) {
if (description.name != profileName) return
_gatewayDescription.value = description
_skillToggleSupported.value = true
_configState.value = LoadState.Loaded(description.toConfigResponse())
_soulState.value = LoadState.Loaded(description.toSoulResponse())
_skillsState.value = LoadState.Loaded(description.toSkillsResponse())
}
private fun saveGatewayPatch(
patch: GatewayProfilePatch,
afterAuthoritativeRefresh: (GatewayProfileConfigureResult, GatewayProfileDescription) -> Unit,
) {
val client = gatewayClient
if (client == null) {
_editEvents.tryEmit(EditEvent.Error("Gateway profile editor unavailable"))
return
}
viewModelScope.launch {
val configured = client.configureProfile(profileName, patch)
if (configured.isFailure) {
clearSavingFlags()
_editEvents.tryEmit(EditEvent.Error(configured.exceptionOrNull()?.message ?: "Save failed"))
return@launch
}
val result = configured.getOrThrow()
val refreshed = client.describeProfile(profileName)
if (refreshed.isFailure) {
clearSavingFlags()
_editEvents.tryEmit(EditEvent.Error(saveSummary(result) + "; authoritative refresh failed"))
return@launch
}
val description = refreshed.getOrThrow()
applyGatewayDescription(description)
afterAuthoritativeRefresh(result, description)
val summary = saveSummary(result)
if (result.applied.isEmpty()) _editEvents.tryEmit(EditEvent.Error(summary))
else _editEvents.tryEmit(EditEvent.Saved(summary))
}
}
private fun clearSavingFlags() {
_configSaving.value = false
_soulSaving.value = false
_skillsSaving.value = false
}
private fun saveSummary(result: GatewayProfileConfigureResult): String {
val applied = result.applied.joinToString { it.wireName }.ifBlank { "none" }
val failed = result.failed.joinToString { it.wireName }.ifBlank { "none" }
return "Applied: $applied; failed: $failed"
}
private fun GatewayProfileDescription.toConfigResponse(): ProfileConfigResponse =
ProfileConfigResponse(
profile = name,
path = "profiles.describe",
readonly = false,
config = buildJsonObject {
put("description", description)
put("model", buildJsonObject {
put("provider", provider)
put("default", model)
})
put("tools", buildJsonObject {
put("toolsets_pinned", toolsetsPinned)
put("enabled_toolsets", JsonArray(toolsets.filter { it.enabled }.map { kotlinx.serialization.json.JsonPrimitive(it.name) }))
})
},
)
private fun GatewayProfileDescription.toSoulResponse(): ProfileSoulResponse =
ProfileSoulResponse(
profile = name,
path = "profiles.describe",
content = soul,
exists = soul.isNotEmpty(),
sizeBytes = soul.toByteArray(Charsets.UTF_8).size.toLong(),
)
private fun GatewayProfileDescription.toSkillsResponse(): ProfileSkillsResponse =
ProfileSkillsResponse(
profile = name,
skills = skills.map {
ProfileSkillEntry(
name = it.name,
category = "Gateway",
description = "",
path = "",
enabled = it.enabled,
)
},
total = skills.size,
)
private fun <T> Result<T>.toLoadState(fallbackMessage: String? = null): LoadState<T> = fold(
onSuccess = { LoadState.Loaded(it) },
onFailure = { LoadState.Error(it.message ?: "Unknown error") },
onFailure = { LoadState.Error(it.message ?: fallbackMessage ?: "Unknown error") },
)
companion object {
/** Nav-arg key for the profile-name path segment. Matches the
* declaration in `Screen.ProfileInspector`. */
const val ARG_PROFILE_NAME: String = "profileName"
}
}
@@ -77,6 +77,9 @@ class UpstreamTransportController(
* `hermes_dashboard_<id>` file (original behavior).
*/
private val tokenStoreKeyProvider: (String) -> String? = { null },
/** Applies pairing-bound TLS to a standard authenticated client when needed. */
private val pinnedClientProvider: (String, okhttp3.OkHttpClient) -> okhttp3.OkHttpClient? =
{ _, _ -> null },
) {
// --- Per-connection dashboard cookie stores ----------------------------
@@ -147,30 +150,34 @@ class UpstreamTransportController(
* factory the dashboard-surface callers (profile lists, session/message
* scoping, the gateway client, standard-API setup probe) route through.
*/
fun dashboardClientFor(connectionId: String, dashboardUrl: String): DashboardApiClient =
DashboardApiClient(
baseUrl = dashboardUrl,
okHttpClient = DashboardApiClient.defaultClient(
cookieStore = dashboardCookieStoreFor(connectionId),
bearerAuth = bearerAuthForTrustedDashboard(connectionId, dashboardUrl),
),
fun dashboardClientFor(connectionId: String, dashboardUrl: String): DashboardApiClient {
val base = DashboardApiClient.defaultClient(
cookieStore = dashboardCookieStoreFor(connectionId),
bearerAuth = bearerAuthForTrustedDashboard(connectionId, dashboardUrl),
)
return DashboardApiClient(
baseUrl = dashboardUrl,
okHttpClient = pinnedClientProvider(dashboardUrl, base) ?: base,
)
}
/**
* Build a [DashboardApiClient] for the active connection against
* [dashboardUrl], falling back to an in-memory cookie store when there is
* no active connection (the standard-voice probe path).
*/
fun dashboardClientForActive(dashboardUrl: String): DashboardApiClient =
DashboardApiClient(
baseUrl = dashboardUrl,
okHttpClient = DashboardApiClient.defaultClient(
cookieStore = activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
bearerAuth = activeConnectionIdProvider()?.let {
bearerAuthForTrustedDashboard(it, dashboardUrl)
},
),
fun dashboardClientForActive(dashboardUrl: String): DashboardApiClient {
val base = DashboardApiClient.defaultClient(
cookieStore = activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
bearerAuth = activeConnectionIdProvider()?.let {
bearerAuthForTrustedDashboard(it, dashboardUrl)
},
)
return DashboardApiClient(
baseUrl = dashboardUrl,
okHttpClient = pinnedClientProvider(dashboardUrl, base) ?: base,
)
}
/**
* Native PKCE client for the active connection's exact trusted dashboard
@@ -190,9 +197,16 @@ class UpstreamTransportController(
) {
return null
}
val base = okhttp3.OkHttpClient.Builder()
.retryOnConnectionFailure(false)
.connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.writeTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
.build()
return NativeDashboardAuthClient(
baseUrl = dashboardUrl,
tokenStore = dashboardTokenStoreFor(connectionId),
client = pinnedClientProvider(dashboardUrl, base) ?: base,
)
}
@@ -205,12 +219,14 @@ class UpstreamTransportController(
disposeDashboardHttpClient(client)
dashboardHttpClientCache = null
}
return DashboardApiClient.defaultClient(
val base = DashboardApiClient.defaultClient(
cookieStore = activeDashboardCookieStore() ?: InMemoryDashboardCookieStore(),
bearerAuth = activeConnectionIdProvider()?.let { activeId ->
bearerAuthForTrustedDashboard(activeId, dashboardUrl)
},
).also { dashboardHttpClientCache = Triple(connectionId, dashboardUrl, it) }
)
return (pinnedClientProvider(dashboardUrl, base) ?: base)
.also { dashboardHttpClientCache = Triple(connectionId, dashboardUrl, it) }
}
@Synchronized
@@ -3834,6 +3834,16 @@
<string name="dashboard_tab_channels_lower">canais</string>
<string name="dashboard_tab_operations_lower">operações</string>
<string name="dashboard_section_action_server_backup">Criar backup do servidor</string>
<string name="dashboard_section_action_download_backup">Salvar backup mais recente</string>
<string name="dashboard_section_action_import_backup">Importar backup</string>
<string name="dashboard_backup_create_first">Crie um backup nesta sessão antes de baixá-lo.</string>
<string name="dashboard_backup_download_failed">Não foi possível baixar o backup.</string>
<string name="dashboard_backup_saved">Backup salvo como %1$s.</string>
<string name="dashboard_import_title">Importar backup do servidor?</string>
<string name="dashboard_import_warning">Isso envia o ZIP selecionado ao Hermes e inicia a importação autenticada no servidor. A configuração e os dados podem ser substituídos. Primeiro, crie e salve um backup atual.</string>
<string name="dashboard_import_confirm">Importar</string>
<string name="dashboard_import_started">Importação do servidor iniciada. Acompanhe a conclusão em Operações antes de reiniciar o Hermes.</string>
<string name="dashboard_import_failed">Não foi possível iniciar a importação do servidor.</string>
<string name="dashboard_profile_mcp_servers_optional">Servidores MCP (opcional)</string>
<string name="dashboard_profile_mcp_servers_help">Nomes de servidor separados por vírgulas ou linhas. As credenciais permanecem no servidor.</string>
<string name="dashboard_tile_memory_title">Memória</string>
@@ -3844,7 +3854,60 @@
<string name="dashboard_tile_channels_sub">Status das plataformas de mensagens, incluindo WhatsApp</string>
<string name="dashboard_tile_operations_title">Operações do servidor</string>
<string name="dashboard_tile_operations_sub">Integridade do host e backup geral do servidor</string>
<string name="dashboard_action_configure">Configurar</string>
<string name="dashboard_action_setup">Configurar</string>
<string name="dashboard_action_setup_whatsapp">Configurar o WhatsApp</string>
<string name="dashboard_learning_edit_title">Editar %1$s</string>
<string name="dashboard_learning_edit_warning">As edições substituem todo o conteúdo do nó. As habilidades excluídas do grafo são arquivadas pelo Hermes e podem ser restauradas; a exclusão de nós de memória é permanente, então exporte um backup primeiro.</string>
<string name="dashboard_learning_saved">Nó de aprendizado salvo.</string>
<string name="dashboard_learning_save_failed">Não foi possível salvar o nó de aprendizado.</string>
<string name="dashboard_learning_delete_warning">O Hermes arquiva as habilidades aprendidas para que possam ser restauradas pelo servidor. A exclusão de nós de memória é permanente. Se este conteúdo puder ser necessário depois, salve primeiro um backup do servidor.</string>
<string name="dashboard_memory_config_title">Configurar %1$s</string>
<string name="dashboard_memory_config_help">Os valores permanecem no perfil do Hermes selecionado. Os campos secretos são aceitos pelo servidor e nunca retornados após o salvamento. Os campos obrigatórios são marcados com *.</string>
<string name="dashboard_memory_values_json">Valores do provedor (JSON)</string>
<string name="dashboard_memory_run_setup">Executar configuração</string>
<string name="dashboard_memory_invalid_json">Os valores do provedor devem formar um objeto JSON.</string>
<string name="dashboard_memory_setup_started">A instalação do provedor em todo o host foi iniciada. Atualize após a conclusão e salve os valores deste perfil.</string>
<string name="dashboard_memory_saved">Provedor de memória configurado e ativado.</string>
<string name="dashboard_memory_save_failed">Não foi possível salvar a configuração do provedor de memória.</string>
<string name="dashboard_whatsapp_title">Configurar o WhatsApp</string>
<string name="dashboard_whatsapp_help">O Hermes inicia uma sessão de pareamento de dez minutos limitada ao perfil. Escolha o modo bot para uma conta dedicada ou conversa própria para enviar mensagens à sua conta vinculada.</string>
<string name="dashboard_whatsapp_bot">Conta de bot</string>
<string name="dashboard_whatsapp_self_chat">Conversa própria</string>
<string name="dashboard_whatsapp_allowed_users">Números de telefone permitidos (opcional)</string>
<string name="dashboard_whatsapp_start">Iniciar pareamento</string>
<string name="dashboard_whatsapp_scan">Escaneie este código na tela Dispositivos conectados do WhatsApp. Mantenha esta caixa de diálogo aberta enquanto o Hermes confirma a conta.</string>
<string name="dashboard_whatsapp_qr">Código QR de dispositivo conectado do WhatsApp</string>
<string name="dashboard_whatsapp_apply">Ativar o WhatsApp</string>
<string name="dashboard_whatsapp_start_failed">Não foi possível iniciar o pareamento do WhatsApp.</string>
<string name="dashboard_whatsapp_apply_failed">Não foi possível salvar a configuração do WhatsApp.</string>
<string name="dashboard_whatsapp_saved">WhatsApp ativado; o Hermes iniciou a reinicialização do gateway.</string>
<string name="drawer_all_profiles">Todos os perfis</string>
<string name="drawer_no_profile_sessions">Nenhuma sessão de perfil correspondente.</string>
<string name="drawer_close">Fechar</string>
<string name="profile_inspector_gateway_settings">Configurações do perfil do Gateway</string>
<string name="profile_inspector_gateway_settings_hint">Salvo diretamente pelo Hermes para este perfil selecionado.</string>
<string name="profile_inspector_edit_config">Editar configurações do perfil</string>
<string name="profile_inspector_description">Descrição</string>
<string name="profile_inspector_provider">Provedor</string>
<string name="profile_inspector_model">Modelo</string>
<string name="profile_inspector_save_changes">Salvar alterações</string>
<string name="profile_inspector_toolsets">Conjuntos de ferramentas</string>
<string name="profile_inspector_toolsets_hint">Escolha quais grupos de ferramentas do Hermes este perfil pode usar.</string>
<string name="profile_inspector_tool_count">%1$d ferramentas</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Experimental</string>
<string name="hermes_reach_summary">Rota de broker experimental para redes onde o acesso direto e o Tailscale não estão disponíveis. Ela ainda não é recomendada para a configuração normal; o TLS do Secure Link continua protegido de ponta a ponta.</string>
<string name="secure_link_pinned_tls">TLS fixado · identidade verificada por este pareamento</string>
<string name="secure_link_pinned_tls_short">Secure Link · TLS fixado</string>
<string name="secure_link_protects">Serviços protegidos: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Painel</string>
<string name="secure_link_no_services">Nenhum serviço protegido foi anunciado. O Secure Link não será usado.</string>
<string name="secure_link_partial_warning">Proteção parcial: os serviços não listados aqui usam sua própria rota e segurança configuradas.</string>
<string name="secure_link_partial_short">Secure Link · parcial</string>
<string name="secure_link_fallback_ready">Se o Secure Link não estiver disponível, o Hermes poderá tentar as rotas alternativas aprovadas abaixo.</string>
<string name="secure_link_no_fallback">Nenhuma rota alternativa está incluída. Os serviços protegidos permanecerão offline se o Secure Link não estiver disponível.</string>
<string name="secure_link_auth_note">A proteção do transporte não ignora a autenticação. O pareamento do Relay, as credenciais da API e o login no Painel continuam sendo exigidos por serviço.</string>
</resources>
@@ -3932,7 +3932,70 @@
<string name="dashboard_tile_channels_sub">消息平台状态,包括 WhatsApp</string>
<string name="dashboard_tile_operations_title">服务器运维</string>
<string name="dashboard_tile_operations_sub">主机健康状况和服务器整体备份</string>
<string name="dashboard_section_action_download_backup">保存最新备份</string>
<string name="dashboard_section_action_import_backup">导入备份</string>
<string name="dashboard_backup_create_first">请先在本次会话中创建备份,再下载。</string>
<string name="dashboard_backup_download_failed">无法下载备份。</string>
<string name="dashboard_backup_saved">备份已保存为 %1$s。</string>
<string name="dashboard_import_title">导入服务器备份?</string>
<string name="dashboard_import_warning">这会将所选 ZIP 上传到 Hermes,并启动经过身份验证的服务器导入。导入可能替换配置和数据。请先创建并保存当前备份。</string>
<string name="dashboard_import_confirm">导入</string>
<string name="dashboard_import_started">服务器导入已启动。请在“运维”中等待完成,然后再重启 Hermes。</string>
<string name="dashboard_import_failed">无法启动服务器导入。</string>
<string name="dashboard_action_configure">配置</string>
<string name="dashboard_action_setup">设置</string>
<string name="dashboard_action_setup_whatsapp">设置 WhatsApp</string>
<string name="dashboard_learning_edit_title">编辑 %1$s</string>
<string name="dashboard_learning_edit_warning">编辑会替换节点的全部内容。Hermes 会归档从图谱中删除的技能,以便从归档中恢复;删除记忆节点则无法撤销,因此请先导出备份。</string>
<string name="dashboard_learning_saved">学习节点已保存。</string>
<string name="dashboard_learning_save_failed">无法保存学习节点。</string>
<string name="dashboard_learning_delete_warning">Hermes 会归档已学习技能,以便从服务器归档中恢复。删除记忆节点则无法撤销。如果以后可能需要这些内容,请先保存服务器备份。</string>
<string name="dashboard_memory_config_title">配置 %1$s</string>
<string name="dashboard_memory_config_help">值会保留在所选 Hermes 配置文件中。服务器接受机密字段,但保存后绝不会返回这些字段。必填字段以 * 标记。</string>
<string name="dashboard_memory_values_json">提供商值 (JSON)</string>
<string name="dashboard_memory_run_setup">运行设置</string>
<string name="dashboard_memory_invalid_json">提供商值必须是 JSON 对象。</string>
<string name="dashboard_memory_setup_started">全主机范围的提供商安装已启动。完成后请刷新,然后保存此配置文件的值。</string>
<string name="dashboard_memory_saved">记忆提供商已配置并启用。</string>
<string name="dashboard_memory_save_failed">无法保存记忆提供商配置。</string>
<string name="dashboard_whatsapp_title">设置 WhatsApp</string>
<string name="dashboard_whatsapp_help">Hermes 会启动一个时长十分钟、仅限当前配置文件的配对会话。专用账号请选择机器人模式;要向自己已关联的账号发消息,请选择自聊。</string>
<string name="dashboard_whatsapp_bot">机器人账号</string>
<string name="dashboard_whatsapp_self_chat">自聊</string>
<string name="dashboard_whatsapp_allowed_users">允许的电话号码(可选)</string>
<string name="dashboard_whatsapp_start">开始配对</string>
<string name="dashboard_whatsapp_scan">请在 WhatsApp 的“关联设备”页面扫描此代码。Hermes 确认账号期间,请保持此对话框打开。</string>
<string name="dashboard_whatsapp_qr">WhatsApp 关联设备二维码</string>
<string name="dashboard_whatsapp_apply">启用 WhatsApp</string>
<string name="dashboard_whatsapp_start_failed">无法开始 WhatsApp 配对。</string>
<string name="dashboard_whatsapp_apply_failed">无法保存 WhatsApp 配置。</string>
<string name="dashboard_whatsapp_saved">WhatsApp 已启用;Hermes 已开始重启网关。</string>
<string name="drawer_all_profiles">所有配置文件</string>
<string name="drawer_no_profile_sessions">没有匹配的配置文件会话。</string>
<string name="drawer_close">关闭</string>
<string name="profile_inspector_gateway_settings">Gateway 配置文件设置</string>
<string name="profile_inspector_gateway_settings_hint">通过 Hermes 直接保存到当前所选配置文件。</string>
<string name="profile_inspector_edit_config">编辑配置文件设置</string>
<string name="profile_inspector_description">说明</string>
<string name="profile_inspector_provider">提供商</string>
<string name="profile_inspector_model">模型</string>
<string name="profile_inspector_save_changes">保存更改</string>
<string name="profile_inspector_toolsets">工具集</string>
<string name="profile_inspector_toolsets_hint">选择此配置文件可以使用的 Hermes 工具组。</string>
<string name="profile_inspector_tool_count">%1$d 个工具</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · 实验性</string>
<string name="hermes_reach_summary">用于无法直接访问且无法使用 Tailscale 的网络的实验性代理路由。目前不建议用于常规设置;Secure Link TLS 仍保持端到端保护。</string>
<string name="secure_link_pinned_tls">固定 TLS · 已通过此次配对验证身份</string>
<string name="secure_link_pinned_tls_short">Secure Link · 固定 TLS</string>
<string name="secure_link_protects">受保护的服务:%1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">控制面板</string>
<string name="secure_link_no_services">未公布任何受保护的服务。不会使用 Secure Link。</string>
<string name="secure_link_partial_warning">部分保护:未在此列出的服务将使用各自配置的路由和安全设置。</string>
<string name="secure_link_partial_short">Secure Link · 部分</string>
<string name="secure_link_fallback_ready">如果 Secure Link 不可用,Hermes 可以尝试下面已批准的备用路由。</string>
<string name="secure_link_no_fallback">未包含备用路由。如果 Secure Link 不可用,受保护的服务将保持离线。</string>
<string name="secure_link_auth_note">传输保护不会绕过身份验证。Relay 配对、API 凭据和控制面板登录仍会按服务分别强制执行。</string>
</resources>
+63
View File
@@ -4004,7 +4004,70 @@
<string name="dashboard_tile_channels_sub">Status der Nachrichtenplattformen einschließlich WhatsApp</string>
<string name="dashboard_tile_operations_title">Serverbetrieb</string>
<string name="dashboard_tile_operations_sub">Hostzustand und serverweite Sicherung</string>
<string name="dashboard_section_action_download_backup">Neueste Sicherung speichern</string>
<string name="dashboard_section_action_import_backup">Sicherung importieren</string>
<string name="dashboard_backup_create_first">Erstellen Sie in dieser Sitzung eine Sicherung, bevor Sie sie herunterladen.</string>
<string name="dashboard_backup_download_failed">Die Sicherung konnte nicht heruntergeladen werden.</string>
<string name="dashboard_backup_saved">Sicherung als %1$s gespeichert.</string>
<string name="dashboard_import_title">Server-Sicherung importieren?</string>
<string name="dashboard_import_warning">Dies lädt die ausgewählte ZIP-Datei zu Hermes hoch und startet den authentifizierten Serverimport. Dabei können Konfiguration und Daten ersetzt werden. Erstellen und speichern Sie zuerst eine aktuelle Sicherung.</string>
<string name="dashboard_import_confirm">Importieren</string>
<string name="dashboard_import_started">Serverimport gestartet. Warten Sie unter „Betrieb“ auf den Abschluss, bevor Sie Hermes neu starten.</string>
<string name="dashboard_import_failed">Der Serverimport konnte nicht gestartet werden.</string>
<string name="dashboard_action_configure">Konfigurieren</string>
<string name="dashboard_action_setup">Einrichten</string>
<string name="dashboard_action_setup_whatsapp">WhatsApp einrichten</string>
<string name="dashboard_learning_edit_title">%1$s bearbeiten</string>
<string name="dashboard_learning_edit_warning">Beim Bearbeiten wird der gesamte Inhalt des Knotens ersetzt. Aus dem Graphen gelöschte Skills werden von Hermes archiviert und können aus dem Archiv wiederhergestellt werden. Das Löschen von Speicherknoten ist endgültig; exportieren Sie daher zuerst eine Sicherung.</string>
<string name="dashboard_learning_saved">Lernknoten gespeichert.</string>
<string name="dashboard_learning_save_failed">Der Lernknoten konnte nicht gespeichert werden.</string>
<string name="dashboard_learning_delete_warning">Hermes archiviert erlernte Skills, sodass sie aus dem Serverarchiv wiederhergestellt werden können. Das Löschen von Speicherknoten ist endgültig. Speichern Sie zuerst eine Server-Sicherung, falls dieser Inhalt später noch benötigt wird.</string>
<string name="dashboard_memory_config_title">%1$s konfigurieren</string>
<string name="dashboard_memory_config_help">Die Werte verbleiben im ausgewählten Hermes-Profil. Vertrauliche Felder werden vom Server akzeptiert und nach dem Speichern nie zurückgegeben. Pflichtfelder sind mit * markiert.</string>
<string name="dashboard_memory_values_json">Anbieterwerte (JSON)</string>
<string name="dashboard_memory_run_setup">Einrichtung starten</string>
<string name="dashboard_memory_invalid_json">Die Anbieterwerte müssen ein JSON-Objekt sein.</string>
<string name="dashboard_memory_setup_started">Die hostweite Anbieterinstallation wurde gestartet. Aktualisieren Sie nach Abschluss die Ansicht und speichern Sie dann die Werte dieses Profils.</string>
<string name="dashboard_memory_saved">Speicheranbieter konfiguriert und aktiviert.</string>
<string name="dashboard_memory_save_failed">Die Konfiguration des Speicheranbieters konnte nicht gespeichert werden.</string>
<string name="dashboard_whatsapp_title">WhatsApp einrichten</string>
<string name="dashboard_whatsapp_help">Hermes startet eine zehnminütige, profilbezogene Kopplungssitzung. Wählen Sie den Bot-Modus für ein eigenes Konto oder den Selbstchat, um Nachrichten an Ihr eigenes verknüpftes Konto zu senden.</string>
<string name="dashboard_whatsapp_bot">Bot-Konto</string>
<string name="dashboard_whatsapp_self_chat">Selbstchat</string>
<string name="dashboard_whatsapp_allowed_users">Zulässige Telefonnummern (optional)</string>
<string name="dashboard_whatsapp_start">Kopplung starten</string>
<string name="dashboard_whatsapp_scan">Scannen Sie diesen Code unter „Verknüpfte Geräte“ in WhatsApp. Lassen Sie diesen Dialog geöffnet, während Hermes das Konto bestätigt.</string>
<string name="dashboard_whatsapp_qr">QR-Code für ein verknüpftes WhatsApp-Gerät</string>
<string name="dashboard_whatsapp_apply">WhatsApp aktivieren</string>
<string name="dashboard_whatsapp_start_failed">Die WhatsApp-Kopplung konnte nicht gestartet werden.</string>
<string name="dashboard_whatsapp_apply_failed">Die WhatsApp-Konfiguration konnte nicht gespeichert werden.</string>
<string name="dashboard_whatsapp_saved">WhatsApp aktiviert; Hermes hat einen Gateway-Neustart gestartet.</string>
<string name="drawer_all_profiles">Alle Profile</string>
<string name="drawer_no_profile_sessions">Keine passenden Profilsitzungen.</string>
<string name="drawer_close">Schließen</string>
<string name="profile_inspector_gateway_settings">Gateway-Profileinstellungen</string>
<string name="profile_inspector_gateway_settings_hint">Wird für dieses ausgewählte Profil direkt über Hermes gespeichert.</string>
<string name="profile_inspector_edit_config">Profileinstellungen bearbeiten</string>
<string name="profile_inspector_description">Beschreibung</string>
<string name="profile_inspector_provider">Anbieter</string>
<string name="profile_inspector_model">Modell</string>
<string name="profile_inspector_save_changes">Änderungen speichern</string>
<string name="profile_inspector_toolsets">Toolsets</string>
<string name="profile_inspector_toolsets_hint">Wähle aus, welche Hermes-Werkzeuggruppen dieses Profil verwenden darf.</string>
<string name="profile_inspector_tool_count">%1$d Werkzeuge</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Experimentell</string>
<string name="hermes_reach_summary">Experimentelle Broker-Route für Netzwerke, in denen direkter Zugriff und Tailscale nicht verfügbar sind. Für die normale Einrichtung wird sie noch nicht empfohlen; Secure-Link-TLS bleibt Ende-zu-Ende geschützt.</string>
<string name="secure_link_pinned_tls">Angeheftetes TLS · Identität aus dieser Kopplung bestätigt</string>
<string name="secure_link_pinned_tls_short">Secure Link · angeheftetes TLS</string>
<string name="secure_link_protects">Geschützte Dienste: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Dashboard</string>
<string name="secure_link_no_services">Es wurden keine geschützten Dienste angekündigt. Secure Link wird nicht verwendet.</string>
<string name="secure_link_partial_warning">Teilweiser Schutz: Nicht aufgeführte Dienste verwenden ihre eigene konfigurierte Route und Sicherheit.</string>
<string name="secure_link_partial_short">Secure Link · teilweise</string>
<string name="secure_link_fallback_ready">Wenn Secure Link nicht verfügbar ist, kann Hermes die genehmigten Ausweichrouten unten versuchen.</string>
<string name="secure_link_no_fallback">Keine Ausweichroute enthalten. Geschützte Dienste bleiben offline, wenn Secure Link nicht verfügbar ist.</string>
<string name="secure_link_auth_note">Transportschutz umgeht keine Authentifizierung. Relay-Kopplung, API-Zugangsdaten und Dashboard-Anmeldung werden weiterhin pro Dienst erzwungen.</string>
</resources>
+63
View File
@@ -3689,7 +3689,70 @@
<string name="dashboard_tile_channels_sub">Estado de plataformas de mensajería, incluido WhatsApp</string>
<string name="dashboard_tile_operations_title">Operaciones del servidor</string>
<string name="dashboard_tile_operations_sub">Estado del host y copia de seguridad del servidor</string>
<string name="dashboard_section_action_download_backup">Guardar la copia más reciente</string>
<string name="dashboard_section_action_import_backup">Importar copia de seguridad</string>
<string name="dashboard_backup_create_first">Crea una copia de seguridad en esta sesión antes de descargarla.</string>
<string name="dashboard_backup_download_failed">No se pudo descargar la copia de seguridad.</string>
<string name="dashboard_backup_saved">Copia de seguridad guardada como %1$s.</string>
<string name="dashboard_import_title">¿Importar copia de seguridad del servidor?</string>
<string name="dashboard_import_warning">Esto sube el ZIP seleccionado a Hermes e inicia la importación autenticada del servidor. Puede reemplazar la configuración y los datos. Crea y guarda primero una copia de seguridad actual.</string>
<string name="dashboard_import_confirm">Importar</string>
<string name="dashboard_import_started">Se inició la importación del servidor. Espera a que termine en Operaciones antes de reiniciar Hermes.</string>
<string name="dashboard_import_failed">No se pudo iniciar la importación del servidor.</string>
<string name="dashboard_action_configure">Configurar</string>
<string name="dashboard_action_setup">Configurar</string>
<string name="dashboard_action_setup_whatsapp">Configurar WhatsApp</string>
<string name="dashboard_learning_edit_title">Editar %1$s</string>
<string name="dashboard_learning_edit_warning">Al editar se reemplaza todo el contenido del nodo. Hermes archiva las habilidades eliminadas del grafo y se pueden restaurar desde el archivo; eliminar un nodo de memoria es permanente, así que exporta primero una copia de seguridad.</string>
<string name="dashboard_learning_saved">Nodo de aprendizaje guardado.</string>
<string name="dashboard_learning_save_failed">No se pudo guardar el nodo de aprendizaje.</string>
<string name="dashboard_learning_delete_warning">Hermes archiva las habilidades aprendidas para poder restaurarlas desde el archivo del servidor. Eliminar un nodo de memoria es permanente. Guarda primero una copia de seguridad del servidor si podrías necesitar este contenido más adelante.</string>
<string name="dashboard_memory_config_title">Configurar %1$s</string>
<string name="dashboard_memory_config_help">Los valores permanecen en el perfil de Hermes seleccionado. El servidor acepta los campos secretos y nunca los devuelve después de guardarlos. Los campos obligatorios están marcados con *.</string>
<string name="dashboard_memory_values_json">Valores del proveedor (JSON)</string>
<string name="dashboard_memory_run_setup">Ejecutar configuración</string>
<string name="dashboard_memory_invalid_json">Los valores del proveedor deben ser un objeto JSON.</string>
<string name="dashboard_memory_setup_started">Se inició la instalación del proveedor en todo el host. Actualiza la vista cuando termine y guarda los valores de este perfil.</string>
<string name="dashboard_memory_saved">Proveedor de memoria configurado y activado.</string>
<string name="dashboard_memory_save_failed">No se pudo guardar la configuración del proveedor de memoria.</string>
<string name="dashboard_whatsapp_title">Configurar WhatsApp</string>
<string name="dashboard_whatsapp_help">Hermes inicia una sesión de vinculación de diez minutos para este perfil. Elige el modo bot para una cuenta exclusiva o el chat contigo mismo para enviar mensajes a tu propia cuenta vinculada.</string>
<string name="dashboard_whatsapp_bot">Cuenta de bot</string>
<string name="dashboard_whatsapp_self_chat">Chat contigo mismo</string>
<string name="dashboard_whatsapp_allowed_users">Números de teléfono permitidos (opcional)</string>
<string name="dashboard_whatsapp_start">Iniciar vinculación</string>
<string name="dashboard_whatsapp_scan">Escanea este código desde la pantalla Dispositivos vinculados de WhatsApp. Mantén abierto este cuadro mientras Hermes confirma la cuenta.</string>
<string name="dashboard_whatsapp_qr">Código QR de dispositivo vinculado de WhatsApp</string>
<string name="dashboard_whatsapp_apply">Activar WhatsApp</string>
<string name="dashboard_whatsapp_start_failed">No se pudo iniciar la vinculación de WhatsApp.</string>
<string name="dashboard_whatsapp_apply_failed">No se pudo guardar la configuración de WhatsApp.</string>
<string name="dashboard_whatsapp_saved">WhatsApp activado; Hermes inició un reinicio del gateway.</string>
<string name="drawer_all_profiles">Todos los perfiles</string>
<string name="drawer_no_profile_sessions">No hay sesiones de perfil coincidentes.</string>
<string name="drawer_close">Cerrar</string>
<string name="profile_inspector_gateway_settings">Ajustes del perfil de Gateway</string>
<string name="profile_inspector_gateway_settings_hint">Se guarda directamente mediante Hermes para este perfil seleccionado.</string>
<string name="profile_inspector_edit_config">Editar ajustes del perfil</string>
<string name="profile_inspector_description">Descripción</string>
<string name="profile_inspector_provider">Proveedor</string>
<string name="profile_inspector_model">Modelo</string>
<string name="profile_inspector_save_changes">Guardar cambios</string>
<string name="profile_inspector_toolsets">Conjuntos de herramientas</string>
<string name="profile_inspector_toolsets_hint">Elige qué grupos de herramientas de Hermes puede usar este perfil.</string>
<string name="profile_inspector_tool_count">%1$d herramientas</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Experimental</string>
<string name="hermes_reach_summary">Ruta de intermediario experimental para redes donde no están disponibles el acceso directo ni Tailscale. Aún no se recomienda para la configuración normal; el TLS de Secure Link sigue protegido de extremo a extremo.</string>
<string name="secure_link_pinned_tls">TLS fijado · identidad verificada desde este emparejamiento</string>
<string name="secure_link_pinned_tls_short">Secure Link · TLS fijado</string>
<string name="secure_link_protects">Servicios protegidos: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Panel</string>
<string name="secure_link_no_services">No se anunciaron servicios protegidos. Secure Link no se utilizará.</string>
<string name="secure_link_partial_warning">Protección parcial: los servicios no incluidos aquí usan su propia ruta y seguridad configuradas.</string>
<string name="secure_link_partial_short">Secure Link · parcial</string>
<string name="secure_link_fallback_ready">Si Secure Link no está disponible, Hermes puede probar las rutas alternativas aprobadas que aparecen abajo.</string>
<string name="secure_link_no_fallback">No se incluye ninguna ruta alternativa. Los servicios protegidos permanecerán sin conexión si Secure Link no está disponible.</string>
<string name="secure_link_auth_note">La protección del transporte no omite la autenticación. El emparejamiento de Relay, las credenciales de API y el inicio de sesión del Panel se siguen aplicando por servicio.</string>
</resources>
+63
View File
@@ -3993,6 +3993,16 @@
<string name="dashboard_tab_channels_lower">チャンネル</string>
<string name="dashboard_tab_operations_lower">運用</string>
<string name="dashboard_section_action_server_backup">サーバーバックアップを作成</string>
<string name="dashboard_section_action_download_backup">最新のバックアップを保存</string>
<string name="dashboard_section_action_import_backup">バックアップをインポート</string>
<string name="dashboard_backup_create_first">ダウンロードする前に、このセッションでバックアップを作成してください。</string>
<string name="dashboard_backup_download_failed">バックアップをダウンロードできませんでした。</string>
<string name="dashboard_backup_saved">バックアップを %1$s として保存しました。</string>
<string name="dashboard_import_title">サーバーバックアップをインポートしますか?</string>
<string name="dashboard_import_warning">選択した ZIP を Hermes にアップロードし、認証済みのサーバーインポートを開始します。設定やデータが置き換わる可能性があります。先に現在のバックアップを作成して保存してください。</string>
<string name="dashboard_import_confirm">インポート</string>
<string name="dashboard_import_started">サーバーのインポートを開始しました。Hermes を再起動する前に、運用画面で完了を確認してください。</string>
<string name="dashboard_import_failed">サーバーのインポートを開始できませんでした。</string>
<string name="dashboard_profile_mcp_servers_optional">MCP サーバー(任意)</string>
<string name="dashboard_profile_mcp_servers_help">サーバー名をカンマまたは改行で区切ります。認証情報はサーバー側に保持されます。</string>
<string name="dashboard_tile_memory_title">メモリ</string>
@@ -4003,7 +4013,60 @@
<string name="dashboard_tile_channels_sub">WhatsApp を含むメッセージプラットフォームの状態</string>
<string name="dashboard_tile_operations_title">サーバー運用</string>
<string name="dashboard_tile_operations_sub">ホストの状態とサーバー全体のバックアップ</string>
<string name="dashboard_action_configure">設定</string>
<string name="dashboard_action_setup">セットアップ</string>
<string name="dashboard_action_setup_whatsapp">WhatsApp を設定</string>
<string name="dashboard_learning_edit_title">%1$sを編集</string>
<string name="dashboard_learning_edit_warning">編集するとノードの内容全体が置き換わります。グラフから削除したスキルは Hermes によってアーカイブされ、復元できます。メモリノードの削除は元に戻せないため、先にバックアップをエクスポートしてください。</string>
<string name="dashboard_learning_saved">学習ノードを保存しました。</string>
<string name="dashboard_learning_save_failed">学習ノードを保存できませんでした。</string>
<string name="dashboard_learning_delete_warning">Hermes は学習済みスキルをアーカイブするため、サーバーのアーカイブから復元できます。メモリノードの削除は元に戻せません。この内容が後で必要になる可能性がある場合は、先にサーバーバックアップを保存してください。</string>
<string name="dashboard_memory_config_title">%1$sを設定</string>
<string name="dashboard_memory_config_help">値は選択した Hermes プロファイルに保持されます。シークレット項目はサーバーに保存されますが、保存後に返されることはありません。必須項目には * が付いています。</string>
<string name="dashboard_memory_values_json">プロバイダーの値(JSON)</string>
<string name="dashboard_memory_run_setup">セットアップを実行</string>
<string name="dashboard_memory_invalid_json">プロバイダーの値は JSON オブジェクトである必要があります。</string>
<string name="dashboard_memory_setup_started">ホスト全体へのプロバイダーのインストールを開始しました。完了後に更新し、このプロファイルの値を保存してください。</string>
<string name="dashboard_memory_saved">メモリプロバイダーを設定して有効にしました。</string>
<string name="dashboard_memory_save_failed">メモリプロバイダーの設定を保存できませんでした。</string>
<string name="dashboard_whatsapp_title">WhatsApp を設定</string>
<string name="dashboard_whatsapp_help">Hermes はプロファイル単位のペアリングセッションを10分間開始します。専用アカウントにはボットモード、自分のリンク済みアカウントへのメッセージにはセルフチャットを選択してください。</string>
<string name="dashboard_whatsapp_bot">ボットアカウント</string>
<string name="dashboard_whatsapp_self_chat">セルフチャット</string>
<string name="dashboard_whatsapp_allowed_users">許可する電話番号(任意)</string>
<string name="dashboard_whatsapp_start">ペアリングを開始</string>
<string name="dashboard_whatsapp_scan">WhatsApp の「リンク済みデバイス」画面でこのコードをスキャンしてください。Hermes がアカウントを確認するまで、このダイアログを開いたままにしてください。</string>
<string name="dashboard_whatsapp_qr">WhatsApp リンク済みデバイスの QR コード</string>
<string name="dashboard_whatsapp_apply">WhatsApp を有効化</string>
<string name="dashboard_whatsapp_start_failed">WhatsApp のペアリングを開始できませんでした。</string>
<string name="dashboard_whatsapp_apply_failed">WhatsApp の設定を保存できませんでした。</string>
<string name="dashboard_whatsapp_saved">WhatsApp を有効にしました。Hermes がゲートウェイの再起動を開始しました。</string>
<string name="drawer_all_profiles">すべてのプロファイル</string>
<string name="drawer_no_profile_sessions">一致するプロファイルセッションはありません。</string>
<string name="drawer_close">閉じる</string>
<string name="profile_inspector_gateway_settings">Gateway プロファイル設定</string>
<string name="profile_inspector_gateway_settings_hint">選択中のプロファイルに Hermes 経由で直接保存します。</string>
<string name="profile_inspector_edit_config">プロファイル設定を編集</string>
<string name="profile_inspector_description">説明</string>
<string name="profile_inspector_provider">プロバイダー</string>
<string name="profile_inspector_model">モデル</string>
<string name="profile_inspector_save_changes">変更を保存</string>
<string name="profile_inspector_toolsets">ツールセット</string>
<string name="profile_inspector_toolsets_hint">このプロファイルで使用できる Hermes のツールグループを選択します。</string>
<string name="profile_inspector_tool_count">%1$d 個のツール</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · 試験機能</string>
<string name="hermes_reach_summary">直接アクセスと Tailscale を利用できないネットワーク向けの試験的なブローカールートです。通常の設定にはまだ推奨されません。Secure Link TLS は引き続きエンドツーエンドで保護されます。</string>
<string name="secure_link_pinned_tls">ピン留め TLS · このペアリングから ID を確認済み</string>
<string name="secure_link_pinned_tls_short">Secure Link · ピン留め TLS</string>
<string name="secure_link_protects">保護されるサービス: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">ダッシュボード</string>
<string name="secure_link_no_services">保護対象のサービスが通知されていません。Secure Link は使用されません。</string>
<string name="secure_link_partial_warning">一部のみ保護: ここにないサービスは、それぞれ設定されたルートとセキュリティを使用します。</string>
<string name="secure_link_partial_short">Secure Link · 一部</string>
<string name="secure_link_fallback_ready">Secure Link を利用できない場合、Hermes は以下の承認済み代替ルートを試行できます。</string>
<string name="secure_link_no_fallback">代替ルートは含まれていません。Secure Link を利用できない場合、保護対象サービスはオフラインのままです。</string>
<string name="secure_link_auth_note">トランスポート保護によって認証が省略されることはありません。Relay のペアリング、API 資格情報、ダッシュボードへのログインはサービスごとに引き続き適用されます。</string>
</resources>
+63
View File
@@ -3725,7 +3725,70 @@
<string name="dashboard_tile_channels_sub">Состояние платформ сообщений, включая WhatsApp</string>
<string name="dashboard_tile_operations_title">Операции сервера</string>
<string name="dashboard_tile_operations_sub">Состояние хоста и резервная копия всего сервера</string>
<string name="dashboard_section_action_download_backup">Сохранить последнюю резервную копию</string>
<string name="dashboard_section_action_import_backup">Импортировать резервную копию</string>
<string name="dashboard_backup_create_first">Перед скачиванием создайте резервную копию в этом сеансе.</string>
<string name="dashboard_backup_download_failed">Не удалось скачать резервную копию.</string>
<string name="dashboard_backup_saved">Резервная копия сохранена как %1$s.</string>
<string name="dashboard_import_title">Импортировать резервную копию сервера?</string>
<string name="dashboard_import_warning">Выбранный ZIP-файл будет загружен в Hermes, после чего начнётся аутентифицированный импорт на сервере. Он может заменить конфигурацию и данные. Сначала создайте и сохраните актуальную резервную копию.</string>
<string name="dashboard_import_confirm">Импортировать</string>
<string name="dashboard_import_started">Импорт на сервере запущен. Перед перезапуском Hermes дождитесь его завершения в разделе «Операции».</string>
<string name="dashboard_import_failed">Не удалось запустить импорт на сервере.</string>
<string name="dashboard_action_configure">Настроить</string>
<string name="dashboard_action_setup">Настройка</string>
<string name="dashboard_action_setup_whatsapp">Настроить WhatsApp</string>
<string name="dashboard_learning_edit_title">Изменить %1$s</string>
<string name="dashboard_learning_edit_warning">Изменения заменят всё содержимое узла. Hermes архивирует навыки, удалённые из графа, чтобы их можно было восстановить из архива; удаление узла памяти необратимо, поэтому сначала экспортируйте резервную копию.</string>
<string name="dashboard_learning_saved">Изученный узел сохранён.</string>
<string name="dashboard_learning_save_failed">Не удалось сохранить изученный узел.</string>
<string name="dashboard_learning_delete_warning">Hermes архивирует изученные навыки, чтобы их можно было восстановить из архива сервера. Удаление узла памяти необратимо. Если содержимое может понадобиться позже, сначала сохраните резервную копию сервера.</string>
<string name="dashboard_memory_config_title">Настроить %1$s</string>
<string name="dashboard_memory_config_help">Значения сохраняются в выбранном профиле Hermes. Секретные поля принимаются сервером и не возвращаются после сохранения. Обязательные поля отмечены символом *.</string>
<string name="dashboard_memory_values_json">Значения провайдера (JSON)</string>
<string name="dashboard_memory_run_setup">Запустить настройку</string>
<string name="dashboard_memory_invalid_json">Значения провайдера должны быть объектом JSON.</string>
<string name="dashboard_memory_setup_started">Установка провайдера на всём хосте запущена. После её завершения обновите данные, затем сохраните значения этого профиля.</string>
<string name="dashboard_memory_saved">Провайдер памяти настроен и активирован.</string>
<string name="dashboard_memory_save_failed">Не удалось сохранить конфигурацию провайдера памяти.</string>
<string name="dashboard_whatsapp_title">Настроить WhatsApp</string>
<string name="dashboard_whatsapp_help">Hermes запускает десятиминутный сеанс привязки для выбранного профиля. Выберите режим бота для отдельной учётной записи или чат с собой, чтобы писать в собственную привязанную учётную запись.</string>
<string name="dashboard_whatsapp_bot">Учётная запись бота</string>
<string name="dashboard_whatsapp_self_chat">Чат с собой</string>
<string name="dashboard_whatsapp_allowed_users">Разрешённые номера телефонов (необязательно)</string>
<string name="dashboard_whatsapp_start">Начать привязку</string>
<string name="dashboard_whatsapp_scan">Отсканируйте этот код на экране «Связанные устройства» в WhatsApp. Не закрывайте это окно, пока Hermes подтверждает учётную запись.</string>
<string name="dashboard_whatsapp_qr">QR-код связанного устройства WhatsApp</string>
<string name="dashboard_whatsapp_apply">Включить WhatsApp</string>
<string name="dashboard_whatsapp_start_failed">Не удалось начать привязку WhatsApp.</string>
<string name="dashboard_whatsapp_apply_failed">Не удалось сохранить конфигурацию WhatsApp.</string>
<string name="dashboard_whatsapp_saved">WhatsApp включён; Hermes начал перезапуск шлюза.</string>
<string name="drawer_all_profiles">Все профили</string>
<string name="drawer_no_profile_sessions">Нет подходящих сеансов профиля.</string>
<string name="drawer_close">Закрыть</string>
<string name="profile_inspector_gateway_settings">Настройки профиля Gateway</string>
<string name="profile_inspector_gateway_settings_hint">Сохраняются напрямую через Hermes для выбранного профиля.</string>
<string name="profile_inspector_edit_config">Изменить настройки профиля</string>
<string name="profile_inspector_description">Описание</string>
<string name="profile_inspector_provider">Провайдер</string>
<string name="profile_inspector_model">Модель</string>
<string name="profile_inspector_save_changes">Сохранить изменения</string>
<string name="profile_inspector_toolsets">Наборы инструментов</string>
<string name="profile_inspector_toolsets_hint">Выберите группы инструментов Hermes, доступные этому профилю.</string>
<string name="profile_inspector_tool_count">Инструментов: %1$d</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Экспериментально</string>
<string name="hermes_reach_summary">Экспериментальный маршрут через брокер для сетей, где недоступны прямое подключение и Tailscale. Он пока не рекомендуется для обычной настройки; TLS Secure Link остаётся защищённым из конца в конец.</string>
<string name="secure_link_pinned_tls">Закреплённый TLS · подлинность подтверждена этим сопряжением</string>
<string name="secure_link_pinned_tls_short">Secure Link · закреплённый TLS</string>
<string name="secure_link_protects">Защищённые сервисы: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Панель</string>
<string name="secure_link_no_services">Защищённые сервисы не объявлены. Secure Link использоваться не будет.</string>
<string name="secure_link_partial_warning">Частичная защита: не указанные здесь сервисы используют собственные настроенные маршруты и параметры безопасности.</string>
<string name="secure_link_partial_short">Secure Link · частично</string>
<string name="secure_link_fallback_ready">Если Secure Link недоступен, Hermes может попробовать одобренные резервные маршруты ниже.</string>
<string name="secure_link_no_fallback">Резервный маршрут не указан. Защищённые сервисы останутся офлайн, если Secure Link недоступен.</string>
<string name="secure_link_auth_note">Защита транспорта не отменяет аутентификацию. Сопряжение Relay, учётные данные API и вход в Панель по-прежнему проверяются отдельно для каждого сервиса.</string>
</resources>
+63
View File
@@ -455,6 +455,21 @@
<string name="cw_step_connect">3. Then come back and tap Connect</string>
<string name="cw_routes_count">Routes (%1$d)</string>
<string name="cw_routes_desc">Your phone tries these routes in order and uses the first one it can reach. It switches automatically as you change networks.</string>
<string name="secure_link_title">Hermes Secure Link</string>
<string name="hermes_reach_title">Hermes Reach · Experimental</string>
<string name="hermes_reach_summary">Experimental broker route for networks where direct access and Tailscale are unavailable. It is not recommended for normal setup yet; Secure Link TLS remains end to end.</string>
<string name="secure_link_pinned_tls">Pinned TLS · identity verified from this pairing</string>
<string name="secure_link_pinned_tls_short">Secure Link · pinned TLS</string>
<string name="secure_link_protects">Protected services: %1$s</string>
<string name="secure_link_service_relay">Relay</string>
<string name="secure_link_service_api">API</string>
<string name="secure_link_service_dashboard">Dashboard</string>
<string name="secure_link_no_services">No protected services were advertised. Secure Link will not be used.</string>
<string name="secure_link_partial_warning">Partial protection: services not listed here use their own configured route and security.</string>
<string name="secure_link_partial_short">Secure Link · partial</string>
<string name="secure_link_fallback_ready">If Secure Link is unavailable, Hermes can try the approved fallback routes below.</string>
<string name="secure_link_no_fallback">No fallback route is included. Protected services will remain offline if Secure Link is unavailable.</string>
<string name="secure_link_auth_note">Transport protection does not bypass authentication. Relay pairing, API credentials, and Dashboard sign-in are still enforced per service.</string>
<string name="cw_prefer_label">Prefer:</string>
<string name="cw_natural_order">Natural order</string>
<string name="cw_keep_pairing_for">Keep this pairing for…</string>
@@ -1977,6 +1992,16 @@
<string name="dashboard_section_action_browse_hub">Browse hub</string>
<string name="dashboard_section_action_update_installed">Update installed</string>
<string name="dashboard_section_action_server_backup">Create server backup</string>
<string name="dashboard_section_action_download_backup">Save latest backup</string>
<string name="dashboard_section_action_import_backup">Import backup</string>
<string name="dashboard_backup_create_first">Create a backup in this session before downloading it.</string>
<string name="dashboard_backup_download_failed">Backup could not be downloaded.</string>
<string name="dashboard_backup_saved">Backup saved as %1$s.</string>
<string name="dashboard_import_title">Import server backup?</string>
<string name="dashboard_import_warning">This uploads the selected zip to Hermes and starts its authenticated server import. It can replace configuration and data. Create and save a current backup first.</string>
<string name="dashboard_import_confirm">Import</string>
<string name="dashboard_import_started">Server import started. Watch Operations for completion before restarting Hermes.</string>
<string name="dashboard_import_failed">Server import could not be started.</string>
<string name="dashboard_profile_mcp_servers_optional">MCP servers (optional)</string>
<string name="dashboard_profile_mcp_servers_help">Comma or line-separated server names. Credentials remain server-owned.</string>
<string name="dashboard_tile_memory_title">Memory</string>
@@ -2010,6 +2035,34 @@
<string name="dashboard_action_use">Use</string>
<string name="dashboard_action_describe">Describe</string>
<string name="dashboard_action_model">Model</string>
<string name="dashboard_action_configure">Configure</string>
<string name="dashboard_action_setup">Setup</string>
<string name="dashboard_action_setup_whatsapp">Set up WhatsApp</string>
<string name="dashboard_learning_edit_title">Edit %1$s</string>
<string name="dashboard_learning_edit_warning">Edits replace the node’s complete content. Skills deleted from the graph are archived by Hermes and can be restored from the archive; memory-node deletion is permanent, so export a backup first.</string>
<string name="dashboard_learning_saved">Learning node saved.</string>
<string name="dashboard_learning_save_failed">Learning node could not be saved.</string>
<string name="dashboard_learning_delete_warning">Hermes archives learned skills so they can be restored from the server archive. Memory-node deletion is permanent. Save a server backup first if this content may be needed later.</string>
<string name="dashboard_memory_config_title">Configure %1$s</string>
<string name="dashboard_memory_config_help">Values stay on the selected Hermes profile. Secret fields are accepted by the server and are never returned after saving. Required fields are marked with *.</string>
<string name="dashboard_memory_values_json">Provider values (JSON)</string>
<string name="dashboard_memory_run_setup">Run setup</string>
<string name="dashboard_memory_invalid_json">Provider values must be a JSON object.</string>
<string name="dashboard_memory_setup_started">Host-wide provider installation started. Refresh after it completes, then save this profile’s values.</string>
<string name="dashboard_memory_saved">Memory provider configured and activated.</string>
<string name="dashboard_memory_save_failed">Memory provider configuration could not be saved.</string>
<string name="dashboard_whatsapp_title">Set up WhatsApp</string>
<string name="dashboard_whatsapp_help">Hermes starts a ten-minute, profile-scoped pairing session. Choose bot mode for a dedicated account or self-chat to message your own linked account.</string>
<string name="dashboard_whatsapp_bot">Bot account</string>
<string name="dashboard_whatsapp_self_chat">Self-chat</string>
<string name="dashboard_whatsapp_allowed_users">Allowed phone numbers (optional)</string>
<string name="dashboard_whatsapp_start">Start pairing</string>
<string name="dashboard_whatsapp_scan">Scan this code from WhatsApp’s Linked devices screen. Keep this dialog open while Hermes confirms the account.</string>
<string name="dashboard_whatsapp_qr">WhatsApp linked-device QR code</string>
<string name="dashboard_whatsapp_apply">Enable WhatsApp</string>
<string name="dashboard_whatsapp_start_failed">WhatsApp pairing could not be started.</string>
<string name="dashboard_whatsapp_apply_failed">WhatsApp configuration could not be saved.</string>
<string name="dashboard_whatsapp_saved">WhatsApp enabled; Hermes started a gateway restart.</string>
<string name="dashboard_mcp_oauth_title">Authenticate %1$s</string>
<string name="dashboard_mcp_oauth_body">Hermes will open the provider in your browser. Return here after approving access; credentials stay on the Hermes server.</string>
<string name="dashboard_mcp_oauth_approved">MCP authentication approved</string>
@@ -4013,4 +4066,14 @@
<string name="drawer_all_profiles">All profiles</string>
<string name="drawer_no_profile_sessions">No matching profile sessions.</string>
<string name="drawer_close">Close</string>
<string name="profile_inspector_gateway_settings">Gateway profile settings</string>
<string name="profile_inspector_gateway_settings_hint">Saved directly through upstream Hermes for this selected profile.</string>
<string name="profile_inspector_edit_config">Edit profile settings</string>
<string name="profile_inspector_description">Description</string>
<string name="profile_inspector_provider">Provider</string>
<string name="profile_inspector_model">Model</string>
<string name="profile_inspector_save_changes">Save changes</string>
<string name="profile_inspector_toolsets">Toolsets</string>
<string name="profile_inspector_toolsets_hint">Choose which upstream tool groups this profile can use.</string>
<string name="profile_inspector_tool_count">%1$d tools</string>
</resources>
@@ -153,11 +153,14 @@ class ChatTurnCheckpointStoreTest {
priorUserMessageCount = 3,
baselineAssistantCount = 3,
pendingAsk = ChatTurnAskCheckpoint(
kind = "APPROVAL",
text = "Allow command?",
kind = "CLARIFY",
requestId = "clarify-1",
text = "Choose environments",
choices = listOf("dev", "prod"),
multiSelect = true,
timeoutSeconds = 0,
messageId = "ask-1",
cardKey = "approval-1",
cardKey = "clarify-1",
receivedAt = 1_004L,
),
queuedMessages = listOf(
@@ -117,4 +117,54 @@ class ConnectionSecurityTest {
assertEquals(ConnectionSecurityLevel.Overlay, result.level)
assertEquals("Tailscale", result.mechanism)
}
@Test
fun relayOnlySecureLink_withPlainStandardServices_isMixed() {
val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
val secureLink = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
url = "https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("relay"),
),
security = "pinned_tls",
)
val result = computeConnectionSecurity(
apiUrl = "http://192.168.1.10:8642",
dashboardUrl = "http://192.168.1.10:9119",
relayUrl = "wss://relay.example:9443/relay/ws",
relayConfigured = true,
activeEndpoint = secureLink,
isTailscaleDetected = false,
)
assertEquals(ConnectionSecurityLevel.Mixed, result.level)
assertEquals(false, result.isEncrypted)
assertEquals(listOf("Plain", "Plain", "Hermes Secure Link"), result.surfaces.map { it.mechanism })
}
@Test
fun completeSecureLink_classifiesEachExactProxyNamespace() {
val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
val secureLink = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
url = "https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
),
security = "pinned_tls",
)
val result = computeConnectionSecurity(
apiUrl = "https://relay.example:9443/api",
dashboardUrl = "https://relay.example:9443/dashboard",
relayUrl = "wss://relay.example:9443/relay/ws",
relayConfigured = true,
activeEndpoint = secureLink,
isTailscaleDetected = false,
)
assertEquals(ConnectionSecurityLevel.Tls, result.level)
assertEquals(true, result.isEncrypted)
assertEquals(setOf("Hermes Secure Link"), result.surfaces.map { it.mechanism }.toSet())
}
}
@@ -0,0 +1,34 @@
package com.hermesandroid.relay.data
import org.junit.Assert.assertEquals
import org.junit.Test
class GatewayProfileEditorModelsTest {
@Test
fun `patch distinguishes omitted sections from empty replace lists`() {
val patch = GatewayProfilePatch(
soul = "",
disabledSkills = emptyList(),
enabledToolsets = emptyList(),
)
assertEquals(
setOf(
GatewayProfileSection.Soul,
GatewayProfileSection.Skills,
GatewayProfileSection.Toolsets,
),
patch.requestedSections,
)
}
@Test
fun `configure result treats every requested non-applied section as failed`() {
val result = GatewayProfileConfigureResult(
requested = setOf(GatewayProfileSection.Description, GatewayProfileSection.Model),
applied = setOf(GatewayProfileSection.Description),
)
assertEquals(setOf(GatewayProfileSection.Model), result.failed)
}
}
@@ -0,0 +1,22 @@
package com.hermesandroid.relay.data
import org.junit.Assert.assertEquals
import org.junit.Test
class HermesCardInputTest {
@Test
fun `multi select answer is an exact ordered deduplicated json array`() {
assertEquals(
"[\"prod\",\"dev\",\"custom, value\"]",
encodeClarifyMultiSelectAnswer(
listOf(" prod ", "dev", "prod", "", "custom, value"),
),
)
}
@Test
fun `zero multi select answers encode as an empty array`() {
assertEquals("[]", encodeClarifyMultiSelectAnswer(emptyList()))
}
}
@@ -0,0 +1,52 @@
package com.hermesandroid.relay.data
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class SecureLinkPresentationTest {
private val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
@Test
fun `wire role is presented as Hermes Secure Link`() {
val candidate = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint("https://relay.example:9443", pinSha256 = pin),
security = "pinned_tls",
)
assertEquals("plugin_proxy", candidate.role)
assertEquals("pinned_tls", candidate.security)
assertEquals("Hermes Secure Link", candidate.displayLabel())
assertEquals("https://relay.example:9443", candidate.presentationRouteUrl())
}
@Test
fun `service inventory is normalized and identifies partial protection`() {
val partial = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
"https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("Relay", "api", "relay", "unknown"),
),
)
assertEquals(listOf("relay", "api"), partial.secureLinkServices())
assertFalse(partial.secureLinkCoversAllServices())
val complete = partial.copy(
proxy = partial.proxy?.copy(surfaces = listOf("relay", "api", "dashboard")),
)
assertTrue(complete.secureLinkCoversAllServices())
}
@Test
fun `invalid pin cannot claim Secure Link protection`() {
val candidate = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint("https://relay.example:9443", pinSha256 = "sha256/bad"),
)
assertFalse(candidate.hasSecureProxy())
assertTrue(candidate.secureLinkServices().isEmpty())
}
}
@@ -4,6 +4,7 @@ import com.hermesandroid.relay.data.ApiEndpoint
import com.hermesandroid.relay.data.DashboardEndpoint
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.RelayEndpoint
import com.hermesandroid.relay.data.ProxyEndpoint
import com.hermesandroid.relay.diagnostics.DiagnosticCategory
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
import kotlinx.coroutines.test.runTest
@@ -83,6 +84,18 @@ class EndpointResolverTest {
assertEquals("lan", winner!!.role)
}
@Test
fun supportedRouteWins_overHigherPriorityExperimentalReach() = runTest {
val resolver = EndpointResolver(fastClient, clock = { clockMillis.get() })
val reach = candidate("outbound_broker", priority = 0, server = reachableServer)
.copy(experimental = true)
val tailscale = candidate("tailscale", priority = 1, server = secondReachableServer)
val winner = resolver.resolve(listOf(reach, tailscale))
assertEquals("tailscale", winner?.role)
}
// ---------------------------------------------------------------
// Test 2 — priority-0 unreachable → falls through to priority-1
// ---------------------------------------------------------------
@@ -431,6 +444,50 @@ class EndpointResolverTest {
assertEquals("/health", secondReachableServer.takeRequest(1, TimeUnit.SECONDS)?.path)
}
@Test
fun secureLinkStandardSurfacesProbeIndependently() {
val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
val candidate = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
url = "https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
),
)
val resolver = EndpointResolver(fastClient)
assertEquals(
"https://relay.example:9443/dashboard/api/status",
resolver.probeRequestUrlForTest(candidate, EndpointSurface.Dashboard),
)
assertEquals(
"https://relay.example:9443/api/health",
resolver.probeRequestUrlForTest(candidate, EndpointSurface.Api),
)
assertEquals(
"https://relay.example:9443/relay/health",
resolver.probeRequestUrlForTest(candidate, EndpointSurface.Relay),
)
}
@Test
fun secureLinkDoesNotProbeUnadvertisedStandardService() {
val candidate = EndpointCandidate(
role = "plugin_proxy",
proxy = ProxyEndpoint(
url = "https://relay.example:9443",
pinSha256 = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
surfaces = listOf("relay"),
),
)
val resolver = EndpointResolver(fastClient)
assertNull(resolver.probeRequestUrlForTest(candidate, EndpointSurface.Dashboard))
assertNull(resolver.probeRequestUrlForTest(candidate, EndpointSurface.Api))
assertNotNull(resolver.probeRequestUrlForTest(candidate, EndpointSurface.Relay))
}
@Test
fun apiHealthProbe_usesGetWhenServerRejectsHead() = runTest {
reachableServer.dispatcher = object : Dispatcher() {
@@ -0,0 +1,169 @@
package com.hermesandroid.relay.network.shared
import com.hermesandroid.relay.data.BrokerEndpoint
import com.hermesandroid.relay.data.EndpointCandidate
import com.hermesandroid.relay.data.ProxyEndpoint
import com.hermesandroid.relay.data.displayLabel
import com.hermesandroid.relay.data.hasHermesReach
import com.hermesandroid.relay.data.isValidHermesReach
import com.hermesandroid.relay.data.replaceHermesReachCredential
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Base64
import java.io.IOException
class HermesReachTransportTest {
private val hostId = canonicalId(1)
private val streamId = canonicalId(2)
private val routeToken = canonicalToken(4)
private val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
@Test
fun routeRequiresWssKnownCredentialAndPinnedInnerSecureLink() {
val broker = BrokerEndpoint(
url = "wss://broker.example/v1/connect",
hostId = hostId,
credentialKind = "bootstrap",
token = routeToken,
)
assertTrue(broker.isValidHermesReach())
assertFalse(broker.copy(url = "ws://broker.example/v1/connect").isValidHermesReach())
assertFalse(broker.copy(credentialKind = "unknown").isValidHermesReach())
val missingInnerTrust = EndpointCandidate(role = "plugin_proxy", broker = broker)
assertFalse(missingInnerTrust.hasHermesReach())
assertNull(missingInnerTrust.hermesReachRouteOrNull())
}
@Test
fun registrationUsesCanonicalV1ShapeAndDoesNotExposeHermesCredentials() {
val route = HermesReachRoute(
brokerUrl = "wss://broker.example",
hostId = hostId,
credentialKind = "route",
token = routeToken,
)
val connectionId = canonicalId(3)
val payload = Json.parseToJsonElement(
HermesReachHandshake.registration(route, connectionId),
).jsonObject
assertEquals("register", payload.getValue("type").jsonPrimitive.content)
assertEquals("1", payload.getValue("protocol_version").jsonPrimitive.content)
assertEquals("client", payload.getValue("role").jsonPrimitive.content)
assertEquals(hostId, payload.getValue("host_id").jsonPrimitive.content)
assertEquals(connectionId, payload.getValue("connection_id").jsonPrimitive.content)
assertEquals("route", payload.getValue("credential_kind").jsonPrimitive.content)
assertEquals(routeToken, payload.getValue("token").jsonPrimitive.content)
assertEquals(setOf("type", "protocol_version", "role", "host_id", "connection_id", "credential_kind", "token"), payload.keys)
}
@Test
fun matchedResponseRequiresV1AndCanonical128BitStreamId() {
assertNull(HermesReachHandshake.validateMatched(
"""{"type":"matched","protocol_version":1,"stream_id":"$streamId"}""",
))
assertTrue(HermesReachHandshake.validateMatched(
"""{"type":"matched","protocol_version":1,"stream_id":"short"}""",
)!!.contains("mismatched"))
assertTrue(HermesReachHandshake.validateMatched(
"""{"type":"matched","protocol_version":2,"stream_id":"$streamId"}""",
)!!.contains("mismatched"))
assertTrue(HermesReachHandshake.validateMatched(
"""{"type":"error","code":"host_offline"}""",
)!!.contains("host_offline"))
}
@Test
fun reachPresentationStillRequiresPinnedSecureLink() {
val candidate = EndpointCandidate(
role = "outbound_broker",
proxy = ProxyEndpoint(
url = "https://paired-host.example:9443",
transportHint = "brokered_tls",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
),
broker = BrokerEndpoint(
url = "wss://broker.example/v1/connect",
hostId = hostId,
credentialKind = "bootstrap",
token = routeToken,
),
)
assertTrue(candidate.hasHermesReach())
assertEquals("Hermes Reach", candidate.displayLabel())
assertEquals("wss://broker.example/v1/connect", candidate.hermesReachRouteOrNull()?.tunnelUrlOrNull())
}
@Test
fun receiveQueueRejectsFrameFloodAndTracksPartialConsumption() {
val input = ReachInputStream()
repeat(REACH_MAX_QUEUED_FRAMES) {
assertTrue(input.offer(byteArrayOf(1, 2, 3)))
}
assertFalse(input.offer(byteArrayOf(4)))
val target = ByteArray(2)
assertEquals(2, input.read(target, 0, target.size))
// The first frame still occupies one frame slot until fully consumed.
assertFalse(input.offer(byteArrayOf(4)))
assertEquals(3, input.read())
assertTrue(input.offer(byteArrayOf(4)))
input.close(IOException("done"))
}
@Test
fun receiveQueueEnforcesAggregateByteLimit() {
val input = ReachInputStream()
repeat(REACH_MAX_QUEUED_BYTES / (1024 * 1024)) {
assertTrue(input.offer(ByteArray(1024 * 1024)))
}
assertFalse(input.offer(byteArrayOf(1)))
input.close(null)
}
@Test
fun durableCredentialRotationOnlyReplacesExactAuthorityAndHostLocator() {
fun candidate(host: String, hostId: String, token: String) = EndpointCandidate(
role = "outbound_broker",
security = "e2ee_pinned_tls",
proxy = ProxyEndpoint(
url = "https://paired-host.example:9443",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
),
broker = BrokerEndpoint(
url = "wss://$host/v1/connect",
hostId = hostId,
credentialKind = "route",
token = token,
),
)
val expected = candidate("broker.example", hostId, routeToken)
val otherHost = candidate("broker.example", canonicalId(9), canonicalToken(9))
val otherAuthority = candidate("other.example", hostId, canonicalToken(8))
val replacement = expected.copy(
broker = expected.broker!!.copy(token = canonicalToken(7)),
)
val updated = replaceHermesReachCredential(
listOf(expected, otherHost, otherAuthority),
expected.broker!!,
replacement,
)
assertEquals(canonicalToken(7), updated[0].broker?.token)
assertEquals(otherHost, updated[1])
assertEquals(otherAuthority, updated[2])
}
private fun canonicalId(seed: Int): String = Base64.getUrlEncoder().withoutPadding()
.encodeToString(ByteArray(16) { (it + seed).toByte() })
private fun canonicalToken(seed: Int): String = Base64.getUrlEncoder().withoutPadding()
.encodeToString(ByteArray(32) { (it + seed).toByte() })
}
@@ -0,0 +1,51 @@
package com.hermesandroid.relay.network.shared
import com.hermesandroid.relay.data.ProxyEndpoint
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class PluginProxyTransportTest {
private val pin = "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
@Test
fun `derives all proxy surfaces from one authority`() {
val routes = ProxyEndpoint(
"https://relay.example:9443",
pinSha256 = pin,
surfaces = listOf("relay", "api", "dashboard"),
)
.toPluginProxyRoutesOrNull()!!
assertEquals("relay.example:9443", routes.authority)
assertEquals("https://relay.example:9443/relay", routes.relayHttpUrl)
assertEquals("wss://relay.example:9443/relay/ws", routes.relayWebSocketUrl)
assertEquals("https://relay.example:9443/api", routes.apiBaseUrl)
assertEquals("https://relay.example:9443/dashboard", routes.dashboardBaseUrl)
}
@Test
fun `rejects incomplete or unsafe proxy advertisements`() {
val invalid = listOf(
ProxyEndpoint("http://relay.example:9443", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443", pinSha256 = null),
ProxyEndpoint("https://relay.example:9443", pinSha256 = "sha256/not-base64"),
ProxyEndpoint("https://user@relay.example:9443", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443?route=x", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443/a/../b", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443/a/%2e%2e/b", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443/a%2fb", pinSha256 = pin),
ProxyEndpoint("https://relay.example:9443/secure", pinSha256 = pin),
)
assertTrue(invalid.all { it.toPluginProxyRoutesOrNull() == null })
}
@Test
fun `proxy pin remains scoped to advertised host and port`() {
val routes = ProxyEndpoint("https://relay.example:9443", pinSha256 = pin)
.toPluginProxyRoutesOrNull()!!
assertEquals("relay.example:9443", routes.authority)
assertNull(ProxyEndpoint("https://relay.example", pinSha256 = "sha256/")
.toPluginProxyRoutesOrNull())
}
}
@@ -16,6 +16,7 @@ import com.hermesandroid.relay.data.VoiceIntentTrace
import com.hermesandroid.relay.network.upstream.models.MessageItem
import com.hermesandroid.relay.network.upstream.models.RelayStreamEventEnvelope
import com.hermesandroid.relay.network.upstream.models.SessionItem
import com.hermesandroid.relay.network.upstream.models.SessionPullRequest
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
@@ -602,6 +603,35 @@ class ChatHandlerTest {
assertTrue(restartedHandler.sessions.value.first { it.sessionId == "archived" }.archived)
}
@Test
fun updateSessions_mapsOptionalWorkspaceAndPullRequestState() {
handler.updateSessions(
listOf(
SessionItem(
id = "coding",
cwd = "/work/repo",
gitBranch = "feature/mobile",
gitRepoRoot = "/work/repo",
pullRequest = SessionPullRequest(
number = 134,
url = "https://github.com/example/repo/pull/134",
state = "open",
draft = true,
),
),
),
)
val session = handler.sessions.value.single()
assertEquals("/work/repo", session.workingDirectory)
assertEquals("feature/mobile", session.gitBranch)
assertEquals("/work/repo", session.gitRepoRoot)
assertEquals(134, session.pullRequestNumber)
assertEquals("https://github.com/example/repo/pull/134", session.pullRequestUrl)
assertEquals("open", session.pullRequestState)
assertTrue(session.pullRequestDraft)
}
@Test
fun setSessionFlagsLocal_supportsOptimisticUpdateAndRollback() {
handler.updateSessions(listOf(SessionItem(id = "s1")))
@@ -920,6 +950,50 @@ class ChatHandlerTest {
assertEquals("Continued after an interrupted turn", msg.content)
}
@Test
fun loadMessageHistory_retainsDurableRowIdsWithoutUsingThemAsUiKeys() {
handler.loadMessageHistory(
listOf(
MessageItem(
id = "user-1",
rowId = 41L,
role = "user",
content = JsonPrimitive("First"),
),
MessageItem(
id = "assistant-1",
rowId = 42L,
role = "assistant",
content = JsonPrimitive("Reply"),
),
),
)
val user = handler.messages.value.first()
assertEquals(41L, user.rowId)
assertEquals("user-1", user.uiKey)
assertEquals(42L, handler.messages.value.last().rowId)
}
@Test
fun rebindSurvivorUserRowIds_replacesPrefixAndClearsUnboundTurns() {
handler.loadMessageHistory(
listOf(
MessageItem(id = "user-1", rowId = 41L, role = "user", content = JsonPrimitive("First")),
MessageItem(id = "assistant-1", rowId = 42L, role = "assistant", content = JsonPrimitive("Reply")),
MessageItem(id = "user-2", rowId = 43L, role = "user", content = JsonPrimitive("Second")),
),
)
handler.rebindSurvivorUserRowIds(listOf(101L))
val messages = handler.messages.value
assertEquals(101L, messages[0].rowId)
assertEquals(42L, messages[1].rowId)
assertNull(messages[2].rowId)
assertEquals(listOf("user-1", "assistant-1", "user-2"), messages.map { it.uiKey })
}
@Test
fun reconcileInterimMessage_collapsesProvisionalFinalBubble() {
handler.addPlaceholderMessage(
@@ -14,11 +14,46 @@ import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assert.assertThrows
import org.junit.Before
import org.junit.Test
import okio.Buffer
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
class DashboardApiClientTest {
@Test
fun `multiplex API routing uses served profiles instead of installed inventory`() {
val status = DashboardStatus(
authRequired = true,
profiles = listOf("default", "research", "excluded"),
gatewayMode = "multiplex",
gateways = listOf(
DashboardGatewayTopology(
profile = "default",
servedProfiles = listOf("default", "research", "research", " "),
),
),
)
assertEquals(listOf("default", "research"), status.multiplexServedProfiles())
assertFalse("excluded" in status.multiplexServedProfiles())
}
@Test
fun `multiplex API routing fails closed without launch gateway served profiles`() {
val status = DashboardStatus(
authRequired = true,
profiles = listOf("default", "research"),
gatewayMode = "multiplex",
gateways = emptyList(),
)
assertTrue(status.multiplexServedProfiles().isEmpty())
}
private lateinit var server: MockWebServer
@Before
@@ -864,6 +899,191 @@ class DashboardApiClientTest {
assertEquals("Review title fallbacks", sessions[1].preview)
}
@Test
fun listSessions_enrichesWorkspaceRowsWithTranscriptBackedPullRequest() = runTest {
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json").setBody(
"""{"sessions":[{"id":"coding-1","title":"Ship it","cwd":"/work/hermes-relay","git_branch":"feature/session-context","git_repo_root":"/work/hermes-relay"}]}""",
),
)
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json").setBody(
"""{"pull_requests":{"coding-1":{"number":134,"url":"https://github.com/example/hermes-relay/pull/134"}},"scanned":["coding-1"]}""",
),
)
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json").setBody(
"""{"ghReady":true,"prs":[{"branch":"feature/session-context","draft":false,"number":134,"state":"open","title":"Session context","url":"https://github.com/example/hermes-relay/pull/134"}]}""",
),
)
val session = DashboardApiClient(baseUrl = server.url("/").toString())
.listSessions()
.getOrThrow()
.single()
assertEquals("/work/hermes-relay", session.cwd)
assertEquals("feature/session-context", session.gitBranch)
assertEquals("/work/hermes-relay", session.gitRepoRoot)
assertEquals(134, session.pullRequest?.number)
assertEquals("https://github.com/example/hermes-relay/pull/134", session.pullRequest?.url)
assertEquals("open", session.pullRequest?.state)
assertEquals(false, session.pullRequest?.draft)
server.takeRequest()
val scanRequest = server.takeRequest()
assertEquals("POST", scanRequest.method)
assertEquals("/api/profiles/sessions/pull-requests", scanRequest.requestUrl!!.encodedPath)
assertEquals(
listOf("coding-1"),
Json.parseToJsonElement(scanRequest.body.readUtf8()).jsonObject["ids"]
?.let { it as JsonArray }
?.map { it.toString().trim('"') },
)
val stateRequest = server.takeRequest()
assertEquals("/api/git/review/pr-list", stateRequest.requestUrl!!.encodedPath)
val stateBody = Json.parseToJsonElement(stateRequest.body.readUtf8()).jsonObject
assertEquals("/work/hermes-relay", stateBody["path"]?.toString()?.trim('"'))
assertEquals(listOf("feature/session-context"), (stateBody["branches"] as JsonArray).map { it.toString().trim('"') })
assertEquals(listOf("134"), (stateBody["numbers"] as JsonArray).map { it.toString() })
}
@Test
fun listSessions_keepsWorkspaceMetadataWhenPullRequestEndpointIsUnavailable() = runTest {
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json").setBody(
"""{"sessions":[{"id":"legacy-1","git_branch":"dev","git_repo_root":"/work/legacy"}]}""",
),
)
server.enqueue(MockResponse().setResponseCode(404).setBody("not found"))
val session = DashboardApiClient(baseUrl = server.url("/").toString())
.listSessions()
.getOrThrow()
.single()
assertEquals("dev", session.gitBranch)
assertEquals("/work/legacy", session.gitRepoRoot)
assertEquals(null, session.pullRequest)
}
@Test
fun listSessions_retriesActiveSessionPullRequestMissAfterBoundedTtl() = runTest {
var now = 1_000L
val client = DashboardApiClient(
baseUrl = server.url("/").toString(),
nowMillis = { now },
)
val sessionList = """{"sessions":[{"id":"active-1","cwd":"/work/repo"}]}"""
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody(sessionList))
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json")
.setBody("""{"pull_requests":{},"scanned":["active-1"]}"""),
)
assertEquals(null, client.listSessions().getOrThrow().single().pullRequest)
server.takeRequest()
server.takeRequest()
now += DashboardApiClient.ACTIVE_SESSION_PR_MISS_TTL_MILLIS - 1
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody(sessionList))
assertEquals(null, client.listSessions().getOrThrow().single().pullRequest)
assertEquals("GET", server.takeRequest().method)
now += 1
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody(sessionList))
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json").setBody(
"""{"pull_requests":{"active-1":{"number":12,"url":"https://github.com/example/repo/pull/12"}},"scanned":["active-1"]}""",
),
)
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json")
.setBody("""{"ghReady":false,"prs":[]}"""),
)
assertEquals(12, client.listSessions().getOrThrow().single().pullRequest?.number)
assertEquals("GET", server.takeRequest().method)
assertEquals("/api/profiles/sessions/pull-requests", server.takeRequest().requestUrl!!.encodedPath)
assertEquals("/api/git/review/pr-list", server.takeRequest().requestUrl!!.encodedPath)
}
@Test
fun listSessions_performsOneFinalScanWhenAnActiveMissBecomesTerminal() = runTest {
val client = DashboardApiClient(baseUrl = server.url("/").toString())
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json")
.setBody("""{"sessions":[{"id":"finishing","cwd":"/work/repo"}]}"""),
)
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json")
.setBody("""{"pull_requests":{},"scanned":["finishing"]}"""),
)
client.listSessions().getOrThrow()
repeat(2) { server.takeRequest() }
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json")
.setBody("""{"sessions":[{"id":"finishing","cwd":"/work/repo","ended_at":2000.0}]}"""),
)
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json").setBody(
"""{"pull_requests":{"finishing":{"number":13,"url":"https://github.com/example/repo/pull/13"}},"scanned":["finishing"]}""",
),
)
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json")
.setBody("""{"ghReady":false,"prs":[]}"""),
)
assertEquals(13, client.listSessions().getOrThrow().single().pullRequest?.number)
repeat(3) { server.takeRequest() }
}
@Test
fun listSessions_scopesPullRequestCacheByProfileAndSessionId() = runTest {
val client = DashboardApiClient(baseUrl = server.url("/").toString())
fun enqueueProfileRead(number: Int) {
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json")
.setBody("""{"sessions":[{"id":"same","cwd":"/work/repo"}]}"""),
)
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json").setBody(
"""{"pull_requests":{"same":{"number":$number,"url":"https://github.com/example/repo/pull/$number"}},"scanned":["same"]}""",
),
)
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json")
.setBody("""{"ghReady":false,"prs":[]}"""),
)
}
enqueueProfileRead(11)
assertEquals(11, client.listSessions(profile = "alpha").getOrThrow().single().pullRequest?.number)
repeat(3) { server.takeRequest() }
enqueueProfileRead(22)
assertEquals(22, client.listSessions(profile = "beta").getOrThrow().single().pullRequest?.number)
repeat(3) { server.takeRequest() }
}
@Test
fun listAllProfileSessions_doesNotGuessAcrossDuplicateSessionIds() = runTest {
server.enqueue(
MockResponse().setHeader("Content-Type", "application/json").setBody(
"""{"sessions":[{"id":"same","profile":"alpha","cwd":"/work/a"},{"id":"same","profile":"beta","cwd":"/work/b"}]}""",
),
)
val sessions = DashboardApiClient(baseUrl = server.url("/").toString())
.listAllProfileSessions()
.getOrThrow()
assertEquals(2, sessions.size)
assertTrue(sessions.all { it.pullRequest == null })
assertEquals("GET", server.takeRequest().method)
}
@Test
fun listAllProfileSessions_preservesOwnerAndCompositeIdentity() = runTest {
server.enqueue(
@@ -1372,6 +1592,155 @@ class DashboardApiClientTest {
assertEquals(true, settings.showReasoning)
assertEquals("off", settings.toolDisplay)
}
@Test
fun serverBackup_createDownloadAndImport_useUpstreamContracts() = runTest {
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"archive":"/srv/backups/a.zip"}"""))
server.enqueue(
MockResponse()
.setHeader("Content-Type", "application/zip")
.setHeader("Content-Disposition", "attachment; filename=\"a.zip\"")
.setBody("archive-bytes"),
)
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"name":"import"}"""))
server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"name":"import"}"""))
val client = DashboardApiClient(baseUrl = server.url("/").toString())
val created = client.createServerBackup().getOrThrow()
val downloadSink = ByteArrayOutputStream()
val downloadedFilename = client.downloadServerBackup(created["archive"]!!.toString().trim('"')) {
downloadSink
}.getOrThrow()
client.importServerBackup("/srv/backups/a.zip").getOrThrow()
val uploadBytes = "zip-data".encodeToByteArray()
client.uploadServerBackup(
filename = "phone.zip",
contentLength = uploadBytes.size.toLong(),
openStream = { ByteArrayInputStream(uploadBytes) },
).getOrThrow()
assertEquals("POST", server.takeRequest().method)
val downloadRequest = server.takeRequest()
assertEquals("/api/ops/backup/download", downloadRequest.requestUrl!!.encodedPath)
assertEquals("/srv/backups/a.zip", downloadRequest.requestUrl!!.queryParameter("archive"))
assertEquals("a.zip", downloadedFilename)
assertEquals("archive-bytes", downloadSink.toString(Charsets.UTF_8.name()))
val importRequest = server.takeRequest()
assertEquals("/api/ops/import", importRequest.requestUrl!!.encodedPath)
assertTrue(importRequest.body.readUtf8().contains(""""archive":"/srv/backups/a.zip""""))
val upload = server.takeRequest()
assertEquals("/api/ops/import-upload", upload.requestUrl!!.encodedPath)
val uploadBody = upload.body.readUtf8()
assertTrue(uploadBody.contains("filename=\"phone.zip\""))
assertTrue(uploadBody.contains("zip-data"))
}
@Test
fun boundedStreamRequestBody_streamsAndEnforcesDeclaredAndObservedLimits() {
val payload = "streamed-archive".encodeToByteArray()
val sink = Buffer()
BoundedStreamRequestBody(payload.size.toLong(), 32L) {
ByteArrayInputStream(payload)
}.writeTo(sink)
assertEquals("streamed-archive", sink.readUtf8())
assertThrows(IllegalArgumentException::class.java) {
BoundedStreamRequestBody(declaredLength = 33L, limitBytes = 32L) {
ByteArrayInputStream(byteArrayOf())
}
}
val oversizedUnknownLength = BoundedStreamRequestBody(null, 8L) {
ByteArrayInputStream("ninebytes".encodeToByteArray())
}
assertThrows(IOException::class.java) { oversizedUnknownLength.writeTo(Buffer()) }
}
@Test
fun copyBounded_streamsDownloadAndRejectsDeclaredAndObservedOverflow() {
val output = ByteArrayOutputStream()
val copied = copyBounded(
ByteArrayInputStream("download".encodeToByteArray()),
output,
declaredLength = 8L,
limitBytes = 16L,
)
assertEquals(8L, copied)
assertEquals("download", output.toString(Charsets.UTF_8.name()))
assertThrows(IllegalArgumentException::class.java) {
copyBounded(ByteArrayInputStream(byteArrayOf()), ByteArrayOutputStream(), 17L, 16L)
}
assertThrows(IOException::class.java) {
copyBounded(
ByteArrayInputStream("seventeen-byte-doc".encodeToByteArray()),
ByteArrayOutputStream(),
declaredLength = null,
limitBytes = 16L,
)
}
}
@Test
fun downloadServerBackup_rejectsDeclaredOversizeBeforeOpeningDestination() = runTest {
server.enqueue(
MockResponse()
.setHeader("Content-Type", "application/zip")
.setHeader("Content-Length", DashboardApiClient.MAX_BACKUP_TRANSFER_BYTES + 1),
)
var destinationOpened = false
val result = DashboardApiClient(baseUrl = server.url("/").toString())
.downloadServerBackup("/srv/backups/oversize.zip") {
destinationOpened = true
ByteArrayOutputStream()
}
assertTrue(result.isFailure)
assertFalse(destinationOpened)
}
@Test
fun learningMutations_preserveNodeIdAndProfile() = runTest {
repeat(3) { server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"content":"body"}""")) }
val client = DashboardApiClient(baseUrl = server.url("/").toString())
client.getLearningNode("memory:MEMORY.md:0", "worker").getOrThrow()
client.updateLearningNode("memory:MEMORY.md:0", "replacement", "worker").getOrThrow()
client.deleteLearningNode("memory:MEMORY.md:0", "worker").getOrThrow()
val get = server.takeRequest()
assertEquals("memory:MEMORY.md:0", get.requestUrl!!.queryParameter("id"))
assertEquals("worker", get.requestUrl!!.queryParameter("profile"))
val put = server.takeRequest()
assertEquals("PUT", put.method)
assertTrue(put.body.readUtf8().contains(""""profile":"worker""""))
val delete = server.takeRequest()
assertEquals("DELETE", delete.method)
assertTrue(delete.body.readUtf8().contains(""""id":"memory:MEMORY.md:0""""))
}
@Test
fun memoryProviderAndWhatsApp_calls_areProfileScoped() = runTest {
repeat(5) { server.enqueue(MockResponse().setHeader("Content-Type", "application/json").setBody("""{"ok":true,"pairing_id":"pair-1","status":"waiting"}""")) }
val client = DashboardApiClient(baseUrl = server.url("/").toString())
val values = Json.parseToJsonElement("""{"url":"https://memory.example"}""").jsonObject
client.getMemoryProviderConfig("honcho", "worker").getOrThrow()
client.updateMemoryProviderConfig("honcho", values, "worker").getOrThrow()
client.selectMemoryProvider("honcho").getOrThrow()
client.startWhatsAppOnboarding("self-chat", "15551234567", "worker").getOrThrow()
client.applyWhatsAppOnboarding("pair-1", "self-chat", "15551234567", "worker").getOrThrow()
assertEquals("worker", server.takeRequest().requestUrl!!.queryParameter("profile"))
assertTrue(server.takeRequest().body.readUtf8().contains(""""values":{"url":"https://memory.example"}"""))
assertTrue(server.takeRequest().body.readUtf8().contains(""""provider":"honcho""""))
val start = server.takeRequest()
assertEquals("/api/messaging/whatsapp/onboarding/start", start.requestUrl!!.encodedPath)
assertTrue(start.body.readUtf8().contains(""""profile":"worker""""))
val apply = server.takeRequest()
assertEquals("/api/messaging/whatsapp/onboarding/pair-1/apply", apply.requestUrl!!.encodedPath)
assertTrue(apply.body.readUtf8().contains(""""profile":"worker""""))
}
}
private fun messagePageResponse(
@@ -10,12 +10,15 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put
import okhttp3.OkHttpClient
import okhttp3.WebSocket
@@ -38,6 +41,7 @@ import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
/**
* [GatewayChatClient] wire tests against a scripted fake tui_gateway:
@@ -92,6 +96,9 @@ class GatewayClientHarness(
put("after_messages", 4)
}
@Volatile
var promptSubmitPayload: JsonObject = buildJsonObject { put("ok", true) }
@Volatile
var reasoningEffort = "medium"
@@ -117,6 +124,12 @@ class GatewayClientHarness(
put("dataUri", "data:image/png;base64,iVBORw0KGgo=")
}
@Volatile
var fileAttachPayload: JsonObject = buildJsonObject {
put("attached", true)
put("ref_text", "@file:notes.txt")
}
/** Methods answered with JSON-RPC -32601 — exercises the legacy-name fallback. */
val methodNotFound: MutableSet<String> = ConcurrentHashMap.newKeySet()
@@ -206,7 +219,7 @@ class GatewayClientHarness(
"session.activate" -> recoveryPayload(
(params["session_id"] as? JsonPrimitive)?.contentOrNull ?: "live-activated",
)
"prompt.submit" -> buildJsonObject { put("ok", true) }
"prompt.submit" -> promptSubmitPayload
"session.interrupt" -> buildJsonObject { put("ok", true) }
"process.list" -> buildJsonObject {
put(
@@ -265,10 +278,7 @@ class GatewayClientHarness(
put("attached", true)
put("pages", 1)
}
"file.attach" -> buildJsonObject {
put("attached", true)
put("ref_text", "@file:notes.txt")
}
"file.attach" -> fileAttachPayload
"clarify.respond", "sudo.respond", "secret.respond" ->
buildJsonObject { put("status", askResponseStatus) }
"approval.respond" -> buildJsonObject { put("resolved", approvalResolved) }
@@ -278,6 +288,35 @@ class GatewayClientHarness(
json.parseToJsonElement("""[["/help","Show help"],["/model","Pick model"]]"""),
)
}
"profiles.describe" -> buildJsonObject {
put("name", (params["name"] as? JsonPrimitive)?.contentOrNull ?: "")
put("description", "Android operator")
put("soul", "# Operator")
put("model", buildJsonObject {
put("provider", "openai")
put("default", "gpt-5.6")
})
put("skills", JsonArray(listOf(buildJsonObject {
put("name", "weather")
put("enabled", false)
})))
put("toolsets", JsonArray(listOf(buildJsonObject {
put("name", "terminal")
put("description", "Run commands")
put("tool_count", 4)
put("enabled", true)
})))
put("toolsets_pinned", true)
}
"profiles.configure" -> buildJsonObject {
put("ok", false)
put("applied", buildJsonObject {
if (params.containsKey("description")) put("description", true)
if (params.containsKey("provider")) put("model", false)
if (params.containsKey("disabled_skills")) put("skills", true)
if (params.containsKey("enabled_toolsets")) put("toolsets", true)
})
}
"pet.thumb" -> petThumbPayload
"model.options" -> buildJsonObject {
put("model", "gpt-5.5")
@@ -627,6 +666,50 @@ class GatewayChatClientTest {
harness.shutdown()
}
@Test
fun `profile editor describes exact profile and maps upstream shape`() = runBlocking {
val description = client.describeProfile("operator").getOrThrow()
assertEquals("operator", description.name)
assertEquals("openai", description.provider)
assertEquals("gpt-5.6", description.model)
assertFalse(description.skills.single().enabled)
assertEquals(4, description.toolsets.single().toolCount)
assertTrue(description.toolsetsPinned)
assertEquals(
"operator",
(harness.awaitRpc("profiles.describe")["name"] as? JsonPrimitive)?.contentOrNull,
)
}
@Test
fun `profile configure is gated by describe and reports every requested section`() = runBlocking {
assertTrue(client.configureProfile("operator", com.hermesandroid.relay.data.GatewayProfilePatch(description = "x")).isFailure)
client.describeProfile("operator").getOrThrow()
val result = client.configureProfile(
"operator",
com.hermesandroid.relay.data.GatewayProfilePatch(
description = "Updated",
provider = "openai",
model = "gpt-5.6-sol",
),
).getOrThrow()
assertEquals(setOf(com.hermesandroid.relay.data.GatewayProfileSection.Description), result.applied)
assertEquals(setOf(com.hermesandroid.relay.data.GatewayProfileSection.Model), result.failed)
}
@Test
fun `profile describe method not found becomes sticky unsupported capability`() = runBlocking {
harness.methodNotFound += "profiles.describe"
assertTrue(client.describeProfile("operator").exceptionOrNull() is com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException)
harness.rpcLog.clear()
assertTrue(client.describeProfile("operator").exceptionOrNull() is com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException)
assertTrue(harness.rpcLog.none { it.first == "profiles.describe" })
}
@Test
fun `happy path - ticket, ready, create, submit, stream, complete`() {
val r = Recorder()
@@ -1418,6 +1501,27 @@ class GatewayChatClientTest {
assertEquals("legacy", result.status)
}
@Test
fun `compress session preserves authoritative lock contention message`() {
val r = Recorder()
client.sendTurn(null, "long job", null, r.callbacks) { r.preflightFailures += it }
harness.awaitServerSocket()
harness.awaitRpc("prompt.submit")
harness.compressPayload = buildJsonObject {
put("compressed", false)
put("lock_held", true)
put("message", "Compression skipped because another request holds the lock.")
}
val result = runBlocking { client.compressSession().getOrThrow() }
assertEquals("noop", result.status)
assertEquals(
"Compression skipped because another request holds the lock.",
result.output,
)
}
// --- Profile-bound sessions (upstream tui_gateway: session.create/resume
// take a `profile` arg; a session's agent is built from it) ---
@@ -1706,7 +1810,7 @@ class GatewayChatClientTest {
),
onPreflightFailure = { r.preflightFailures += it },
)
harness.awaitRpc("prompt.submit")
val submit = harness.awaitRpc("prompt.submit")
val attach = harness.awaitRpc("file.attach")
assertEquals("live-1", (attach["session_id"] as? JsonPrimitive)?.contentOrNull)
@@ -1715,11 +1819,67 @@ class GatewayChatClientTest {
(attach["data_url"] as? JsonPrimitive)?.contentOrNull,
)
assertEquals("notes.txt", (attach["name"] as? JsonPrimitive)?.contentOrNull)
assertEquals(
"@file:notes.txt\n\nread this",
(submit["text"] as? JsonPrimitive)?.contentOrNull,
)
assertTrue(harness.rpcLog.none { it.first == "image.attach_bytes" })
assertTrue(harness.rpcLog.none { it.first == "pdf.attach" })
assertTrue(r.preflightFailures.isEmpty())
}
@Test
fun `queued document follow-up keeps its returned file reference on the queued prompt`() {
val r = Recorder()
client.sendTurn(
sessionId = null,
text = "compare the totals",
newSessionTitle = null,
callbacks = r.callbacks,
attachments = listOf(
GatewayAttachment(
name = "quarterly report.ods",
base64 = "UEsDBA==",
ext = "ods",
contentType = "application/vnd.oasis.opendocument.spreadsheet",
),
),
queuedFollowUp = true,
onPreflightFailure = { r.preflightFailures += it },
)
val submit = harness.awaitRpc("prompt.submit")
assertEquals(true, (submit["queued"] as? JsonPrimitive)?.booleanOrNull)
assertEquals(
"@file:notes.txt\n\ncompare the totals",
(submit["text"] as? JsonPrimitive)?.contentOrNull,
)
assertTrue(r.preflightFailures.isEmpty())
}
@Test
fun `document upload without a readable reference fails before prompt submit`() {
harness.fileAttachPayload = buildJsonObject { put("attached", true) }
val r = Recorder()
client.sendTurn(
sessionId = null,
text = "read this",
newSessionTitle = null,
callbacks = r.callbacks,
attachments = listOf(
GatewayAttachment("notes.txt", "aGk=", "txt", "text/plain"),
),
onPreflightFailure = {
r.preflightFailures += it
r.completeLatch.countDown()
},
)
assertTrue(r.completeLatch.await(5, TimeUnit.SECONDS))
assertTrue(r.preflightFailures.single().contains("no readable file reference"))
assertTrue(harness.rpcLog.none { it.first == "prompt.submit" })
}
// --- Ask responders ---
@Test
@@ -2199,6 +2359,41 @@ class GatewayChatClientTest {
assertFalse(submit.containsKey("confirm_empty_truncate"))
}
@Test
fun `durable rewind target and survivor row ids round trip`() {
harness.promptSubmitPayload = buildJsonObject {
put("ok", true)
put("survivor_user_row_ids", buildJsonArray {
add(JsonPrimitive(101L))
add(JsonNull)
add(JsonPrimitive("malformed"))
})
}
val r = Recorder()
val rebound = AtomicReference<List<Long?>>()
val reboundLatch = CountDownLatch(1)
client.sendTurn(
sessionId = "stored-1",
text = "edited message",
newSessionTitle = null,
callbacks = r.callbacks,
truncateBeforeUserOrdinal = 2,
truncateBeforeRowId = 73L,
onSurvivorUserRowIds = {
rebound.set(it)
reboundLatch.countDown()
},
onPreflightFailure = { r.preflightFailures += it },
)
val submit = harness.awaitRpc("prompt.submit")
assertEquals(2, (submit["truncate_before_user_ordinal"] as? JsonPrimitive)?.intOrNull)
assertEquals(73L, (submit["truncate_before_row_id"] as? JsonPrimitive)?.longOrNull)
assertTrue(reboundLatch.await(5, TimeUnit.SECONDS))
assertEquals(listOf(101L, null, null), rebound.get())
}
@Test
fun `first user truncate carries empty-history confirmation`() {
val r = Recorder()
@@ -2262,9 +2457,13 @@ class GatewayChatClientTest {
@Test
fun `authoritative prompt rejections surface server message without preflight fallback`() {
val cases = listOf(
4004 to "Truncation target must be an integer",
4018 to "Target user message is no longer in session history",
4028 to "Empty-history truncate confirmation required",
4029 to "Truncate confirmation required",
4030 to "Row id and ordinal identify different user turns",
4090 to "Active session limit reached; close the session held by another client",
5008 to "Failed to persist history truncation",
5070 to "Session storage is full; free disk space and retry",
5071 to "Initial session persistence failed",
)
@@ -2282,6 +2481,25 @@ class GatewayChatClientTest {
}
}
@Test
fun `bounded transcript resume rejection stays visible and never creates a replacement session`() {
val message =
"Session has 20,001 active messages, above sessions.max_resume_messages; export or raise the limit"
harness.rpcErrors["session.resume"] = 4130 to message
val r = Recorder()
client.sendTurn("oversized-session", "continue", null, r.callbacks) {
r.preflightFailures += it
}
harness.awaitRpc("session.resume")
assertTrue(r.completeLatch.await(5, TimeUnit.SECONDS))
assertEquals(listOf(message), r.errors.toList())
assertTrue(r.preflightFailures.isEmpty())
assertEquals(0, harness.rpcLog.count { it.first == "session.create" })
assertEquals(0, harness.rpcLog.count { it.first == "prompt.submit" })
}
// --- HRUI-016: long / fire-and-forget prompt.submit ack semantics.
// Upstream treats prompt.submit as a long-running RPC (desktop passes a
// 30-min PROMPT_SUBMIT_REQUEST_TIMEOUT_MS at every call site) because the
@@ -715,8 +715,44 @@ class GatewayEventMapperTest {
assertEquals("r1", ask.requestId)
assertEquals("Which file?", ask.text)
assertEquals(listOf("a.txt", "b.txt"), ask.choices)
assertFalse(ask.multiSelect)
assertNull(ask.envVar)
assertEquals(300, ask.timeoutSeconds)
assertEquals(0, ask.timeoutSeconds)
}
@Test
fun `clarify request carries multi select only with bounded usable choices`() {
val r = Recorder()
mapperWith(r).onEvent(
"clarify.request",
obj(
"""{"request_id":"r1","question":"Where?","multi_select":true,"choices":""" +
"""[" dev ","prod","dev","","stage","canary","extra"]}""",
),
)
val ask = r.interactions.single()
assertTrue(ask.multiSelect)
assertEquals(listOf("dev", "prod", "stage", "canary"), ask.choices)
assertEquals(0, ask.timeoutSeconds)
}
@Test
fun `clarify ignores malformed multi select and consumes additive timeout metadata`() {
val r = Recorder()
val mapper = mapperWith(r)
mapper.onEvent(
"clarify.request",
obj("""{"request_id":"r1","multi_select":true,"choices":null,"timeout_seconds":42}"""),
)
mapper.onEvent(
"clarify.request",
obj("""{"request_id":"r2","multi_select":false,"choices":["a"]}"""),
)
assertFalse(r.interactions[0].multiSelect)
assertEquals(42, r.interactions[0].timeoutSeconds)
assertFalse(r.interactions[1].multiSelect)
}
@Test
@@ -758,6 +794,32 @@ class GatewayEventMapperTest {
assertTrue(ask.smartDenied)
}
@Test
fun `approval request removes explicitly forbidden persistent scopes`() {
val r = Recorder()
mapperWith(r).onEvent(
"approval.request",
obj(
"""{"command":"<write to AGENTS.md>","choices":["once","session","always","deny"],"allow_session":false,"allow_permanent":false}""",
),
)
assertEquals(listOf("once", "deny"), r.interactions.single().choices)
}
@Test
fun `approval request retains session while permanent scope is forbidden`() {
val r = Recorder()
mapperWith(r).onEvent(
"approval.request",
obj(
"""{"command":"guarded command","choices":["once","session","always","deny"],"allow_session":true,"allow_permanent":false}""",
),
)
assertEquals(listOf("once", "session", "deny"), r.interactions.single().choices)
}
@Test
fun `tool output risk maps deterministic non-low metadata only`() {
val r = Recorder()
@@ -94,6 +94,18 @@ class SessionModelsTest {
assertTrue(item.archived)
}
@Test
fun sessionItem_deserializesOptionalWorkspaceMetadata() {
val item = json.decodeFromString<SessionItem>(
"""{"id":"s1","cwd":"/work/repo","git_branch":"feature/mobile","git_repo_root":"/work/repo"}""",
)
assertEquals("/work/repo", item.cwd)
assertEquals("feature/mobile", item.gitBranch)
assertEquals("/work/repo", item.gitRepoRoot)
assertNull(item.pullRequest)
}
@Test
fun sessionItem_deserialization_acceptsIsoUpdatedAtFallback() {
val jsonStr = """
@@ -133,6 +145,10 @@ class SessionModelsTest {
assertNull(item.outputTokens)
assertEquals(false, item.pinned)
assertEquals(false, item.archived)
assertNull(item.cwd)
assertNull(item.gitBranch)
assertNull(item.gitRepoRoot)
assertNull(item.pullRequest)
}
// --- SessionListResponse ---
@@ -285,6 +301,27 @@ class SessionModelsTest {
assertNull(item.finishReason)
}
@Test
fun messageItem_rowIdIsMixedVersionSafe() {
assertEquals(
73L,
json.decodeFromString<MessageItem>(
"""{"role":"user","row_id":73}""",
).rowId,
)
assertEquals(
74L,
json.decodeFromString<MessageItem>(
"""{"role":"user","row_id":"74"}""",
).rowId,
)
assertNull(
json.decodeFromString<MessageItem>(
"""{"role":"user","row_id":{"unexpected":true}}""",
).rowId,
)
}
@Test
fun messageItem_roundTrip() {
val original = MessageItem(
@@ -9,16 +9,19 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.click
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.test.click
import androidx.compose.ui.test.swipeDown
import androidx.compose.ui.test.swipeUp
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.hermesandroid.relay.data.HermesCard
import com.hermesandroid.relay.data.HermesCardAction
import com.hermesandroid.relay.data.HermesCardInput
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
@@ -112,6 +115,38 @@ class HermesApprovalCardInteractionTest {
compose.runOnIdle { assertEquals(listOf("once", "deny"), actions) }
}
@Test
fun `multi select clarify toggles choices and submits one ordered json array`() {
val answers = mutableListOf<String>()
compose.setContent {
MaterialTheme {
HermesCardBubble(
card = HermesCard(
type = HermesCard.BuiltInTypes.ASK_CLARIFY,
title = "Choose environments",
input = HermesCardInput(
kind = HermesCardInput.Kinds.CHOICE,
choices = listOf("dev", "stage", "prod"),
multiSelect = true,
allowFreeText = true,
),
),
cardKey = "clarify-multi",
dispatches = emptyList(),
onActionTap = { _, _ -> },
onInputSubmit = { _, value -> answers += value },
)
}
}
compose.onNodeWithText("Submit").assertIsNotEnabled()
compose.onNodeWithText("prod").performTouchInput { click() }
compose.onNodeWithText("dev").performTouchInput { click() }
compose.onNodeWithText("Submit").assertIsEnabled().performTouchInput { click() }
compose.runOnIdle { assertEquals(listOf("[\"prod\",\"dev\"]"), answers) }
}
private fun approvalCard() = HermesCard(
type = HermesCard.BuiltInTypes.ASK_APPROVAL,
title = "Approval requested",
@@ -49,6 +49,34 @@ class SessionDrawerTest {
)
}
@Test
fun `session work labels use a safe repo name branch and pull request number`() {
val session = ChatSession(
sessionId = "coding-1",
title = "Ship it",
model = null,
gitRepoRoot = "C:\\worktrees\\hermes-relay\\",
gitBranch = "feature/android-session-context",
pullRequestNumber = 134,
pullRequestUrl = "https://github.com/example/hermes-relay/pull/134",
pullRequestState = "open",
)
assertEquals(
listOf("hermes-relay", "feature/android-session-context", "PR #134 · Open"),
sessionWorkLabels(session),
)
}
@Test
fun `session work labels stay empty on older hosts`() {
assertTrue(
sessionWorkLabels(
ChatSession(sessionId = "legacy", title = null, model = null),
).isEmpty(),
)
}
@Test
fun `reordered leading session remains visible after drawer refresh`() {
var sessions by mutableStateOf(
@@ -0,0 +1,22 @@
package com.hermesandroid.relay.ui.screens
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ProfileInspectorEditorPolicyTest {
@Test
fun `config save requires complete model identity and an idle request`() {
assertFalse(profileConfigSaveEnabled("", "gpt-5.6", saving = false))
assertFalse(profileConfigSaveEnabled("openai", "", saving = false))
assertFalse(profileConfigSaveEnabled("openai", "gpt-5.6", saving = true))
assertTrue(profileConfigSaveEnabled("openai", "gpt-5.6", saving = false))
}
@Test
fun `gateway save action appears for either kind of retained draft`() {
assertFalse(gatewayDraftSaveVisible(emptyMap(), emptyMap()))
assertTrue(gatewayDraftSaveVisible(mapOf("weather" to false), emptyMap()))
assertTrue(gatewayDraftSaveVisible(emptyMap(), mapOf("terminal" to false)))
}
}
@@ -10,6 +10,7 @@ import com.hermesandroid.relay.data.ChatTurnCheckpoint
import com.hermesandroid.relay.data.ChatTurnCheckpointStore
import com.hermesandroid.relay.data.ChatTurnToolCheckpoint
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
import com.hermesandroid.relay.data.HermesCardDispatch
import com.hermesandroid.relay.data.MessageRole
import com.hermesandroid.relay.network.upstream.ChatHandler
import com.hermesandroid.relay.network.upstream.DashboardApiClient
@@ -26,6 +27,7 @@ import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import okhttp3.OkHttpClient
@@ -660,6 +662,106 @@ class ChatViewModelGatewayInboundTurnTest {
assertEquals("once", cardMessage.cardDispatches.single().actionValue)
}
@Test
fun protectedInstructionApprovalCardOffersOneOperationScopeOnly() {
viewModel.sendMessage("Edit the disposable instruction fixture")
gatewayHarness.awaitRpc("prompt.submit")
serverWs.send(
gatewayHarness.eventFrame(
"approval.request",
buildJsonObject {
put("command", "<write to AGENTS.md>")
put("allow_session", false)
put("allow_permanent", false)
put("choices", buildJsonArray {
add(JsonPrimitive("once"))
add(JsonPrimitive("session"))
add(JsonPrimitive("always"))
add(JsonPrimitive("deny"))
})
},
"live-resumed",
),
)
awaitCondition { viewModel.pendingAsk.value != null }
val pending = requireNotNull(viewModel.pendingAsk.value)
val card = handler.messages.value.single { it.id == pending.messageId }.cards.single()
assertEquals(listOf("once", "deny"), card.actions.map { it.value })
}
@Test
fun multiSelectClarifyPreservesCardSemanticsAndExactWireAnswer() {
viewModel.sendMessage("Ask which environments")
gatewayHarness.awaitRpc("prompt.submit")
serverWs.send(
gatewayHarness.eventFrame(
"clarify.request",
buildJsonObject {
put("request_id", "clarify-1")
put("question", "Which environments?")
put("multi_select", true)
put("choices", buildJsonArray {
add(JsonPrimitive("dev"))
add(JsonPrimitive("stage"))
add(JsonPrimitive("prod"))
})
},
"live-resumed",
),
)
awaitCondition { viewModel.pendingAsk.value != null }
val pending = requireNotNull(viewModel.pendingAsk.value)
val card = handler.messages.value.single { it.id == pending.messageId }.cards.single()
assertTrue(card.input?.multiSelect == true)
assertEquals(listOf("dev", "stage", "prod"), card.input?.choices)
assertEquals(null, card.input?.expiresAtMillis)
viewModel.answerAsk(pending.messageId, pending.cardKey, "[\"prod\",\"dev\"]")
val response = gatewayHarness.awaitRpc("clarify.respond")
assertEquals(JsonPrimitive("clarify-1"), response["request_id"])
assertEquals(JsonPrimitive("[\"prod\",\"dev\"]"), response["answer"])
awaitCondition { viewModel.pendingAsk.value == null }
}
@Test
fun authoritativeClarifyExpiryCollapsesCardAndRejectsLateAction() {
viewModel.sendMessage("Ask a question")
gatewayHarness.awaitRpc("prompt.submit")
serverWs.send(
gatewayHarness.eventFrame(
"clarify.request",
buildJsonObject {
put("request_id", "clarify-expired")
put("question", "Still there?")
put("choices", buildJsonArray { add(JsonPrimitive("yes")) })
},
"live-resumed",
),
)
awaitCondition { viewModel.pendingAsk.value != null }
val pending = requireNotNull(viewModel.pendingAsk.value)
serverWs.send(
gatewayHarness.eventFrame(
"clarify.expire",
buildJsonObject { put("request_id", "clarify-expired") },
"live-resumed",
),
)
awaitCondition { viewModel.pendingAsk.value == null }
val cardMessage = handler.messages.value.single { it.id == pending.messageId }
assertEquals(
HermesCardDispatch.EXPIRED_STAMP,
cardMessage.cardDispatches.single().actionValue,
)
viewModel.answerAsk(pending.messageId, pending.cardKey, "yes")
Thread.sleep(100)
assertTrue(gatewayHarness.rpcLog.none { it.first == "clarify.respond" })
}
@Test
fun explicitDenialActionEmitsResponseAndCollapsesCard() {
viewModel.sendMessage("Run the guarded command")
@@ -0,0 +1,144 @@
package com.hermesandroid.relay.viewmodel
import androidx.lifecycle.SavedStateHandle
import com.hermesandroid.relay.data.GatewayProfileConfigureResult
import com.hermesandroid.relay.data.GatewayProfileDescription
import com.hermesandroid.relay.data.GatewayProfileEditorClient
import com.hermesandroid.relay.data.GatewayProfileEditorUnsupportedException
import com.hermesandroid.relay.data.GatewayProfilePatch
import com.hermesandroid.relay.data.GatewayProfileSection
import com.hermesandroid.relay.data.LegacyProfileInspectorClient
import com.hermesandroid.relay.data.ProfileConfigResponse
import com.hermesandroid.relay.data.ProfileMemoryResponse
import com.hermesandroid.relay.data.ProfileMemoryUpdateResponse
import com.hermesandroid.relay.data.ProfileSkillsResponse
import com.hermesandroid.relay.data.ProfileSoulResponse
import com.hermesandroid.relay.data.ProfileSoulUpdateResponse
import com.hermesandroid.relay.data.RelaySkillToggleResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import kotlinx.serialization.json.buildJsonObject
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class ProfileInspectorViewModelTest {
private val dispatcher = StandardTestDispatcher()
@Before fun setUp() { Dispatchers.setMain(dispatcher) }
@After fun tearDown() { Dispatchers.resetMain() }
@Test
fun `partial gateway save refreshes authoritative sections and retains failed draft`() = runTest(dispatcher) {
val initial = description(description = "Old", model = "old")
val refreshed = description(description = "Updated", model = "old")
val gateway = FakeGateway(
descriptions = mutableListOf(initial, refreshed),
configureResult = GatewayProfileConfigureResult(
requested = setOf(GatewayProfileSection.Description, GatewayProfileSection.Model),
applied = setOf(GatewayProfileSection.Description),
),
)
val viewModel = viewModel(gateway, FakeLegacy())
viewModel.loadAll()
advanceUntilIdle()
viewModel.beginConfigEdit()
viewModel.updateConfigDescriptionDraft("Updated")
viewModel.updateConfigModelDraft("new")
viewModel.saveConfigEdit()
advanceUntilIdle()
assertEquals("operator", gateway.requestedNames.distinct().single())
assertEquals("Updated", viewModel.configDescriptionDraft.value)
assertEquals("new", viewModel.configModelDraft.value)
assertTrue(viewModel.configEditing.value)
assertEquals("old", viewModel.gatewayDescription.value?.model)
}
@Test
fun `older gateway falls back to legacy inspector without changing profile namespace`() = runTest(dispatcher) {
val legacy = FakeLegacy()
val gateway = object : GatewayProfileEditorClient {
override suspend fun describeProfile(profileName: String) =
Result.failure<GatewayProfileDescription>(GatewayProfileEditorUnsupportedException())
override suspend fun configureProfile(profileName: String, patch: GatewayProfilePatch) =
error("configure must remain capability gated")
}
val viewModel = viewModel(gateway, legacy)
viewModel.loadAll()
advanceUntilIdle()
assertEquals(ProfileInspectorSource.Relay, viewModel.source.value)
assertEquals(listOf("operator"), legacy.configRequests)
assertTrue(viewModel.configState.value is LoadState.Loaded)
}
private fun viewModel(
gateway: GatewayProfileEditorClient?,
legacy: LegacyProfileInspectorClient,
) = ProfileInspectorViewModel(
legacyClient = legacy,
gatewayClient = gateway,
savedStateHandle = SavedStateHandle(mapOf(ProfileInspectorViewModel.ARG_PROFILE_NAME to "operator")),
)
private fun description(description: String, model: String) = GatewayProfileDescription(
name = "operator",
description = description,
soul = "# Soul",
provider = "openai",
model = model,
skills = emptyList(),
toolsets = emptyList(),
toolsetsPinned = false,
)
private class FakeGateway(
private val descriptions: MutableList<GatewayProfileDescription>,
private val configureResult: GatewayProfileConfigureResult,
) : GatewayProfileEditorClient {
val requestedNames = mutableListOf<String>()
override suspend fun describeProfile(profileName: String): Result<GatewayProfileDescription> {
requestedNames += profileName
return Result.success(descriptions.removeAt(0))
}
override suspend fun configureProfile(
profileName: String,
patch: GatewayProfilePatch,
): Result<GatewayProfileConfigureResult> {
requestedNames += profileName
return Result.success(configureResult)
}
}
private class FakeLegacy : LegacyProfileInspectorClient {
val configRequests = mutableListOf<String>()
override suspend fun fetchConfig(profileName: String): Result<ProfileConfigResponse> {
configRequests += profileName
return Result.success(ProfileConfigResponse(profileName, "config.yaml", buildJsonObject {}))
}
override suspend fun fetchSkills(profileName: String) =
Result.success(ProfileSkillsResponse(profileName, emptyList(), 0))
override suspend fun fetchSoul(profileName: String) =
Result.success(ProfileSoulResponse(profileName, "SOUL.md", "", false, 0))
override suspend fun fetchMemory(profileName: String) =
Result.success(ProfileMemoryResponse(profileName, "memories", emptyList(), 0))
override suspend fun updateSoul(profileName: String, content: String) =
Result.success(ProfileSoulUpdateResponse(true, profileName, "SOUL.md", content.length.toLong()))
override suspend fun updateMemoryEntry(profileName: String, filename: String, content: String) =
Result.success(ProfileMemoryUpdateResponse(true, profileName, filename, filename, content.length.toLong()))
override suspend fun updateSkillToggle(skillName: String, enabled: Boolean) =
Result.success<RelaySkillToggleResult>(RelaySkillToggleResult.Ok)
override suspend fun probeSkillToggleSupported() = false
}
}
+79 -29
View File
@@ -32,41 +32,68 @@ binary and one set of state files; the tray does not bundle a private sidecar.
Clicking the tray icon toggles the management popup. Paired Hermes instances are
shown as **Hosts**; clients authenticated to the selected host appear separately
under Settings and can be deauthorized there. **Pair another host...** is the
in that host's detail page and can be deauthorized there. **Pair another host...** is the
last host-selector option, or the selector's only action when no hosts exist.
The tray cross-checks the daemon heartbeat and PID, labels the account as
**User** or **Administrator**, and disables lifecycle actions that do not apply
to the current state. **Start/Restart daemon as Administrator...** uses the
standard Windows UAC prompt; the tray itself stays unelevated. Settings can
check the Desktop release channel and self-update the CLI and management UI
together. The installer download is verified against the release
to the current state. **Restart as Administrator...** uses the standard Windows
UAC prompt; the tray itself stays unelevated. **Return to user mode** stops the
elevated daemon once and starts it again with normal user privileges. Because
every approved command and input action inherits the daemon's privilege,
Administrator mode is an explicit action rather than a persistent toggle.
Settings is reserved for this PC. **Start UI at sign-in** controls only the tray
startup entry; the separate **Start daemon with UI** preference decides whether
opening the tray also connects remote access. Automatic daemon startup is off
for existing installs until explicitly enabled. Settings also exposes **Open
terminal**, **Open Hermes CLI**, **View daemon log**, and **Run diagnostics**,
and manages Desktop release updates. **Help &
About** reports the UI, CLI, and connected Relay versions and links to the docs,
troubleshooting, release notes, logs, and diagnostics. The installer download is
verified against the release
`SHA256SUMS.txt`, preserves the startup preference, restores a previously
running daemon, and relaunches the tray after the silent replacement.
Access is selected per host. **Ask** keeps the connection available but attaches
no desktop tools. **Trusted** enables command and file tools while screen/input
still uses task grants. **Full Access** also allows screen, keyboard, and mouse
without task grants for that host; authentication, audit, deauthorization,
emergency stop, and UAC boundaries still apply.
Access is selected per host. **Restricted** keeps the connection available but
attaches no desktop tools. **Ask Every Time** advertises available command, file,
screen/input, and USB operations but requires local approval for each one. It is
the default for newly paired hosts; existing hosts retain their stored policy.
**Standard** enables typed operations while withholding
raw terminal, PowerShell, detached-process, and command-job launch. **Full Access**
allows every available capability without task grants for that host;
authentication, audit, deauthorization, emergency stop, and UAC boundaries
still apply. Commands, Files, Screen & Input, Raw USB, Microphone, and Camera
form one per-host capability ledger. Changing an individual gate selects an exact
preset when the resulting combination matches one and otherwise creates a
**Custom** policy. Existing `ask`, `structured`, and `trusted` CLI values remain
accepted as compatibility aliases; legacy `ask` still means Restricted, while
the new preset is `ask-every-time`. Raw USB gates direct native/vendor USB utility
execution plus secondary services such as ADB. Microphone and camera remain
unavailable until their controlled paths exist.
The tray's **Activity** section is a live, local view of recent remote actions
and management events such as daemon, host-access, grant, client, and update
changes.
It groups events into commands, files, screen, and input; highlights failures,
It groups events into commands, files, screen, input, and connected devices; highlights failures,
aborts, and non-zero process exits; and keeps request context collapsed until
explicitly expanded. Events record handler duration and request ID where
available. The compact Overview still shows only the three newest events.
Settings also keeps activity compact: it previews the three newest events and
opens a dedicated Activity detail page for wrapped filters and expandable
records. Handler failures and aborts are **Issues**; non-zero process exits are
opens a dedicated Activity page. Selecting an event opens bounded request,
stdout, stderr, result, exit, timing, and truncation evidence; sensitive request
inputs are excluded. Handler failures and aborts are **Issues**; non-zero process exits are
shown separately because probing commands may legitimately use them. **Clear**
removes both current and rotated local audit history after confirmation.
Clicking a card under **Hosts** opens that host's detail page; it does not change
the active connection. The detail page can set a local display name and has an
explicit connect action. Local names are stored in `desktop-control.json` and
do not rename the remote Hermes instance.
the active connection. The detail page is the per-host hub for its local display
name, connection state, Relay address and version, pairing/session details,
access, capabilities, and authorized clients. It also provides explicit connect,
re-pair, deauthorize-client, and guarded **Forget host** actions. Local names are
stored in `desktop-control.json` and do not rename the remote Hermes instance.
Forgetting removes the local session, alias, and access policy; deauthorization
is the separate action that removes a server-side client session.
## Install
@@ -241,6 +268,13 @@ relay one-shot code.
Now subsequent `hermes-relay ...` calls reuse the stored session token. Tokens live at `~/.hermes/remote-sessions.json` (mode 0600) — same file the Ink TUI uses, so pairing once from either surface works for both.
Each desktop installation also keeps a private stable identifier in
`~/.hermes/desktop-device-id`. This lets several PCs retain independent paired
sessions on one Relay. Re-pairing one PC replaces only that installation's old
credential. Every desktop RPC accepts a stable device ID or unambiguous computer
name. With several connected daemons the target is required, preventing an
agent command from silently following the most recent connection.
### Terminal plugins
The `hermes-relay plugins` command exposes optional terminal surfaces. The first
@@ -260,13 +294,18 @@ Herm uses `bun add -g herm-tui` when Bun is available and falls back to
### Host access and daemon bring-up
Starting the daemon no longer grants tools and no longer requires a tool grant.
With a paired host in **Ask**, it connects in locked mode with zero desktop tools.
With a paired host in **Restricted**, it connects in locked mode with zero desktop tools.
Select a host policy from the tray or use the CLI:
```sh
hermes-relay hosts list --json
hermes-relay hosts select ws://192.168.1.100:8767
hermes-relay hosts access trusted --remote ws://192.168.1.100:8767
hermes-relay hosts access ask-every-time --remote ws://192.168.1.100:8767
hermes-relay hosts access standard --remote ws://192.168.1.100:8767
hermes-relay hosts capability commands allow --remote ws://192.168.1.100:8767 --yes
hermes-relay hosts capability files ask --remote ws://192.168.1.100:8767
hermes-relay hosts capability screen-input ask --remote ws://192.168.1.100:8767
hermes-relay hosts capability usb ask --remote ws://192.168.1.100:8767
hermes-relay daemon start
```
@@ -336,7 +375,13 @@ The relay discovers background server-side tmux sessions named `hermes-*`, so `s
### Multi-endpoint pairing (ADR 24)
If your Hermes server is reachable via multiple routes (LAN + Tailscale + a public URL), the pairing invite encoded by the host QR carries all of them. Pass the printed `hermes-relay://pair?...` URL, raw JSON payload, or base64 payload to `--pair-qr` and the CLI probes in priority order, picks the first reachable endpoint, and records which route it used — subsequent connects show `Connected via LAN (plain)` / `Connected via Tailscale (secure)` etc.
If your Hermes server is reachable via multiple routes (optional Hermes Secure Link, Tailscale, a public TLS URL, and LAN), the pairing invite encoded by the host QR carries all of them. Generated defaults prefer Secure Link when enabled, then other secure routes, with plain LAN retained as a fallback. Pass the printed `hermes-relay://pair?...` URL, raw JSON payload, or base64 payload to `--pair-qr`; the CLI probes in strict priority order, picks the first reachable endpoint, and records which route it used. Secure Link protects transport to the QR-paired endpoint but does not create reachability, and its Relay, API, and Dashboard credentials remain separate.
**Hermes Reach** is an experimental outbound-broker fallback. The broker
provides rendezvous while the CLI validates QR-pinned Secure Link TLS inside
it, but Reach is never selected ahead of Tailscale, public TLS, or Direct Secure
Link by default. It is disabled unless the host explicitly opts into the
experimental feature. Reach failure never enables plaintext.
```sh
# Paste the full pairing invite URL printed by hermes-pair:
@@ -385,7 +430,7 @@ overrides. The per-host policy is stored separately in
`~/.hermes/desktop-host-access.json`; Full Access enables this surface for its
host without an expiring task grant.
In Ask or Trusted mode, observe grants allow screenshots;
When Screen & Input is set to Ask, observe grants allow screenshots;
assist/control grants require explicit local approval before host input can run.
The daemon writes pending requests to `~/.hermes/grant-bridge`; review them with
`hermes-relay grants` or the tray's focused approval dialog. Grants
@@ -504,7 +549,7 @@ hermes-relay audit --json
```
```
Desktop-tool activity (4 most recent)
Desktop-tool activity (3 most recent)
WHEN TOOL STATUS DETAIL
12s ago desktop_read_file ● ok path=C:\src\app.ts
@@ -531,6 +576,8 @@ hermes-relay relay security # runtime auth toggles (run on the relay host)
hermes-relay daemon start # run in the background (no console window)
hermes-relay daemon status # state + uptime of the running daemon
hermes-relay daemon restart # restart with the caller's current privileges
hermes-relay daemon restart --administrator # Windows: request UAC and run elevated
hermes-relay daemon restart --user # Windows: return to normal user mode
hermes-relay daemon stop # stop it
hermes-relay daemon # run in the FOREGROUND (current console)
```
@@ -553,15 +600,18 @@ hermes-relay daemon
`status` reads the heartbeat file a running daemon maintains and cross-checks that the pid is alive — it exits non-zero (and says "not running") when the daemon is gone, so scripts can branch on it.
On Windows, keep the tray and normal daemon unelevated for routine operation.
Use **Start/Restart daemon as Administrator...** only when a desktop action
requires administrator access. Windows displays UAC consent, and the elevated
daemon records its privilege level in the same status file so later stop and
restart actions preserve the required elevation.
Use **Restart as Administrator...** only when a desktop action requires
administrator access. Windows displays UAC consent, and the elevated daemon
records its privilege level in the same status file so the UI can label it
clearly. Use **Return to user mode** to stop it once and start a normal daemon.
The equivalent CLI actions are `daemon restart --administrator` and `daemon
restart --user`; both are Windows-only and mutually exclusive.
> **Auto-start on boot/login:** the Windows menu can start the tray at user
> sign-in; it intentionally does not auto-elevate or silently start an
> Administrator daemon. Starting the daemon itself as a service still needs an
> OS service, systemd user unit, or launchd agent.
> **Auto-start on boot/login:** **Start UI at sign-in** registers the tray at
> user sign-in. **Start daemon with UI** is a separate opt-in and remains off
> for existing installs until enabled. Neither option auto-elevates or starts
> an Administrator daemon. Starting the daemon itself as a machine service
> still needs an OS service, systemd user unit, or launchd agent.
## Flags and environment
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@hermes-relay/cli",
"version": "0.4.0-alpha.7",
"version": "0.4.0-alpha.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@hermes-relay/cli",
"version": "0.4.0-alpha.7",
"version": "0.4.0-alpha.8",
"license": "MIT",
"bin": {
"hermes-relay": "bin/hermes-relay.js"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@hermes-relay/cli",
"version": "0.4.0-alpha.7",
"version": "0.4.0-alpha.8",
"description": "Thin-client CLI for Hermes-Relay — talk to a remote Hermes agent over WSS with pairing auth, stream-renders tool calls and responses to plain stdout.",
"type": "module",
"bin": {
@@ -49,7 +49,7 @@
"dev:install": "node scripts/dev-install.mjs",
"dev:install:tray": "npm run dev:install && node scripts/dev-install-tray.mjs",
"type-check": "tsc --noEmit -p tsconfig.json",
"test": "tsx --test tests/**/*.test.ts",
"test": "tsx --test --test-concurrency=1 tests/**/*.test.ts",
"clean": "rimraf dist"
},
"engines": {
+21
View File
@@ -40,6 +40,27 @@ export const extractSpkiSha256 = (peerCertDer: Buffer): string => {
return `${PIN_PREFIX}${digest}`
}
/** Read the leaf DER across supported Node TLS APIs. Node 24 can return an
* empty legacy PeerCertificate for a valid TLS 1.3 connection while the
* X509Certificate API remains populated. Prefer the modern API and retain the
* legacy fallback for Node 21-23. */
export const peerCertificateDer = (socket: {
getPeerX509Certificate?: () => { raw?: Buffer } | undefined
getPeerCertificate?: (detailed?: boolean) => { raw?: Buffer }
}): Buffer | null => {
const modern = socket.getPeerX509Certificate?.()?.raw
if (Buffer.isBuffer(modern) && modern.length > 0) return modern
const legacy = socket.getPeerCertificate?.(false)?.raw
return Buffer.isBuffer(legacy) && legacy.length > 0 ? legacy : null
}
/** Convert the already pin-verified leaf to a PEM trust anchor for the live
* WebSocket handshake. This binds the live connection to the checked cert. */
export const certificateDerToPem = (der: Buffer): string => {
const base64 = der.toString('base64').match(/.{1,64}/g)?.join('\n') ?? ''
return `-----BEGIN CERTIFICATE-----\n${base64}\n-----END CERTIFICATE-----\n`
}
/**
* Canonical pin-store key for a URL — lowercase `host:port`. Explicit port
* is required (no implicit 443/80) so `wss://host/` and `wss://host:443/`
+3
View File
@@ -67,6 +67,9 @@ const BOOLEAN_FLAGS = new Set([
'log-json',
'status',
'detach',
'administrator',
'user',
'elevation-child',
'allow-tools',
'allow-computer-use',
'experimental-computer-use',
+15 -3
View File
@@ -48,6 +48,9 @@ import {
shouldAdvertiseComputerUse
} from '../tools/handlerSet.js'
import { DesktopToolRouter } from '../tools/router.js'
import { effectiveHostAccessMode, effectiveHostCapabilityPolicies, getHostAccessMode, getHostCapabilityPolicies } from '../lib/hostAccessPolicy.js'
import { configureCapabilityPolicies } from '../tools/capabilityRuntime.js'
import { adbBackendAvailable } from '../tools/handlers/adb.js'
import { PROMPT_SUBMIT_REQUEST_TIMEOUT_MS, RelayTransport } from '../transport/RelayTransport.js'
// (getSession is imported above with the other remoteSessions exports so we
@@ -129,6 +132,7 @@ async function connectAndAuth(args: ParsedArgs): Promise<AuthedRelay> {
relay.onAuthSuccess((token, ver, meta) => {
void saveSession(url, token, ver, {
initializeAccessPolicy: true,
grants: meta.grants,
ttlExpiresAt: meta.ttlExpiresAt,
endpointRole
@@ -584,16 +588,24 @@ export async function chatCommand(args: ParsedArgs): Promise<number> {
const consent = await ensureToolsConsent(url)
if (consent.consented) {
const computerUseEnabled = shouldAdvertiseComputerUse(args.flags)
const storedAccessMode = await getHostAccessMode(url)
const accessMode = effectiveHostAccessMode(storedAccessMode, consent.consented)
const capabilities = effectiveHostCapabilityPolicies(storedAccessMode, consent.consented, await getHostCapabilityPolicies(url))
configureCapabilityPolicies(capabilities)
const usb = capabilities.usb !== 'disabled'
const adb = usb && adbBackendAvailable()
configureComputerUseRuntime({
url,
computerUseConsented: computerUseEnabled,
consentSource: consent.source ?? 'stored'
consentSource: consent.source ?? 'stored',
accessMode,
capabilities
})
const advertisedTools = advertisedDesktopTools({ computerUse: computerUseEnabled })
const advertisedTools = advertisedDesktopTools({ computerUse: computerUseEnabled, capabilities, usb, adb })
toolRouter = new DesktopToolRouter({
consentGranted: true,
hostUrl: url,
handlers: desktopHandlers({ computerUse: computerUseEnabled }),
handlers: desktopHandlers({ computerUse: computerUseEnabled, capabilities, usb, adb }),
advertisedTools: [...advertisedTools]
})
toolRouter.attach(relay)
+248 -13
View File
@@ -36,6 +36,7 @@ import * as path from 'node:path'
import type { ParsedArgs } from '../cli.js'
import { desktopRelayIdentity } from '../deviceIdentity.js'
import { inferEndpointRole } from '../endpoint.js'
import { GatewayClient } from '../gatewayClient.js'
import type { GatewayEvent, SessionCreateResponse } from '../gatewayTypes.js'
import {
@@ -49,11 +50,12 @@ import {
type DaemonStatus
} from '../lib/daemonStatus.js'
import { rpcErrorMessage, asRpcResult } from '../lib/rpc.js'
import { effectiveHostAccessMode, getHostAccessMode } from '../lib/hostAccessPolicy.js'
import { effectiveHostAccessMode, effectiveHostCapabilityPolicies, getHostAccessMode, getHostCapabilityPolicies } from '../lib/hostAccessPolicy.js'
import { theme as makeTheme } from '../lib/theme.js'
import { printUsage, type UsageSpec } from '../lib/usage.js'
import { resolveFirstRunUrl } from '../relayUrlPrompt.js'
import { getSession } from '../remoteSessions.js'
import { probeCandidatesByPriority, secureFirstCandidates } from '../pairingQr.js'
import {
advertisedDesktopTools,
desktopHandlers,
@@ -67,6 +69,8 @@ import {
type ComputerGrant
} from '../tools/computerGrants.js'
import { DesktopToolRouter } from '../tools/router.js'
import { configureCapabilityPolicies } from '../tools/capabilityRuntime.js'
import { adbBackendAvailable } from '../tools/handlers/adb.js'
import { RelayTransport } from '../transport/RelayTransport.js'
import { setupGracefulExit } from '../lib/gracefulExit.js'
import { grantBridgeDir } from '../lib/grantBridge.js'
@@ -85,16 +89,24 @@ const DETACHED_START_POLL_MS = 100
const DAEMON_USAGE: UsageSpec = {
name: 'daemon',
summary: 'run headless — expose desktop tools to the agent even when no shell is open',
usage: ['daemon [run]', 'daemon start', 'daemon stop', 'daemon restart', 'daemon status'],
usage: [
'daemon [run]',
'daemon start [--administrator]',
'daemon stop [--administrator]',
'daemon restart [--administrator|--user]',
'daemon status'
],
subcommands: [
{ verb: 'run', desc: 'Run in the foreground (current console; default)' },
{ verb: 'start', desc: 'Start in the background — no console window; survives terminal close' },
{ verb: 'stop', desc: 'Stop the background daemon' },
{ verb: 'restart', desc: 'Restart the background daemon, preserving caller privileges' },
{ verb: 'restart', desc: 'Restart the background daemon, preserving caller privileges by default' },
{ verb: 'status', desc: 'Print state + uptime of the running daemon (alias: --status)' }
],
flags: [
{ flag: '--detach', desc: 'Alias for `daemon start` — run in the background' },
{ flag: '--administrator', desc: 'Windows: explicitly request UAC and run the daemon as Administrator' },
{ flag: '--user', desc: 'Windows: restart the daemon as the current unelevated user' },
{ flag: '--remote <url>', desc: 'Relay to connect to (default: stored/active session)' },
{ flag: '--token <token>', desc: 'Use an explicit session token (CI/provisioning)' },
{ flag: '--allow-tools', desc: 'Skip the stored-consent gate (only with --token; implies trust)' },
@@ -106,7 +118,8 @@ const DAEMON_USAGE: UsageSpec = {
examples: [
'hermes-relay daemon start',
'hermes-relay daemon status',
'hermes-relay daemon restart',
'hermes-relay daemon restart --administrator',
'hermes-relay daemon restart --user',
'hermes-relay daemon stop'
]
}
@@ -353,6 +366,116 @@ function buildDaemonChildArgs(args: ParsedArgs): string[] {
return out
}
type DaemonLifecycleSubcommand = 'start' | 'stop' | 'restart'
interface ElevationLaunchPlan {
program: string
args: string[]
env: NodeJS.ProcessEnv
targetProgram: string
targetArgs: string[]
}
/** Quote one argv item for CommandLineToArgvW. Start-Process accepts a single
* ArgumentList string, so preserve spaces, quotes, and trailing backslashes. */
function quoteWindowsArgument(value: string): string {
if (value.length > 0 && !/[\s"]/u.test(value)) return value
let out = '"'
let slashes = 0
for (const char of value) {
if (char === '\\') {
slashes += 1
continue
}
if (char === '"') {
out += '\\'.repeat(slashes * 2 + 1) + '"'
slashes = 0
continue
}
out += '\\'.repeat(slashes) + char
slashes = 0
}
return out + '\\'.repeat(slashes * 2) + '"'
}
function executableInvocationPrefix(): { program: string; args: string[] } {
const execIsNode = /node(\.exe)?$/i.test(path.basename(process.execPath))
return {
program: process.execPath,
args: execIsNode ? [process.argv[1] ?? ''] : []
}
}
/** Build the UAC launcher separately from execution so the exact privilege
* boundary and forwarded argv are regression-testable. */
function buildElevationLaunchPlan(
args: ParsedArgs,
subcommand: DaemonLifecycleSubcommand
): ElevationLaunchPlan {
const invocation = executableInvocationPrefix()
const targetArgs = [
...invocation.args,
'daemon',
subcommand,
...buildDaemonChildArgs(args).slice(1),
'--elevation-child'
]
const commandLine = targetArgs.map(quoteWindowsArgument).join(' ')
const script = [
"$ErrorActionPreference = 'Stop'",
'$argumentLine = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:HERMES_RELAY_ELEVATE_ARGS))',
'try {',
" $child = Start-Process -FilePath $env:HERMES_RELAY_ELEVATE_PROGRAM -ArgumentList $argumentLine -Verb RunAs -WindowStyle Hidden -Wait -PassThru",
' exit $child.ExitCode',
'} catch {',
" [Console]::Error.WriteLine('Administrator request failed or was canceled: ' + $_.Exception.Message)",
' exit 1',
'}'
].join('\n')
return {
program: 'powershell.exe',
args: ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script],
env: {
...process.env,
HERMES_RELAY_ELEVATE_PROGRAM: invocation.program,
HERMES_RELAY_ELEVATE_ARGS: Buffer.from(commandLine, 'utf8').toString('base64')
},
targetProgram: invocation.program,
targetArgs
}
}
async function runElevatedDaemonLifecycle(
args: ParsedArgs,
subcommand: DaemonLifecycleSubcommand
): Promise<number> {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
if (process.platform !== 'win32') {
process.stderr.write(t.err('--administrator is supported only on Windows') + '\n')
return 1
}
const plan = buildElevationLaunchPlan(args, subcommand)
return new Promise(resolve => {
let settled = false
const child = spawn(plan.program, plan.args, {
env: plan.env,
stdio: 'inherit',
windowsHide: true
})
child.once('error', error => {
if (settled) return
settled = true
process.stderr.write(t.err(`failed to request Administrator access: ${error.message}`) + '\n')
resolve(1)
})
child.once('exit', code => {
if (settled) return
settled = true
resolve(code === 0 ? 0 : 1)
})
})
}
/** `daemon start` / `--detach` — spawn the foreground daemon as a detached
* background process (no console window on Windows), logging to a file. */
async function startDetachedDaemon(args: ParsedArgs): Promise<number> {
@@ -503,12 +626,70 @@ async function restartDaemon(args: ParsedArgs): Promise<number> {
return startDetachedDaemon(args)
}
async function restartDaemonAsUser(args: ParsedArgs): Promise<number> {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
const identity = currentProcessIdentity()
if (identity.privilege === 'administrator') {
process.stderr.write(
t.err('cannot launch a user daemon from an Administrator process; run this command from the normal desktop UI or an unelevated terminal') + '\n'
)
return 1
}
const existing = await readDaemonStatus()
if (
process.platform === 'win32' &&
existing &&
isDaemonProcessAlive(existing) &&
existing.privilege === 'administrator'
) {
// An unelevated caller cannot terminate an elevated daemon. Elevate only
// the stop operation, wait for it to finish, then start the replacement
// from this original unelevated process.
const stopped = await runElevatedDaemonLifecycle(args, 'stop')
if (stopped !== 0) return stopped
return startDetachedDaemon(args)
}
return restartDaemon(args)
}
export async function daemonCommand(args: ParsedArgs): Promise<number> {
if (args.flags.help) {
printUsage(DAEMON_USAGE, makeTheme({ noColor: !!args.flags['no-color'] }))
return 0
}
const sub = args.positional[0]
const administrator = args.flags.administrator === true
const user = args.flags.user === true
const elevationChild = args.flags['elevation-child'] === true
if ((administrator || user || elevationChild) && process.platform !== 'win32') {
process.stderr.write('daemon: --administrator and --user are supported only on Windows\n')
return 1
}
if (administrator && user) {
process.stderr.write('daemon: --administrator and --user are mutually exclusive\n')
return 1
}
if ((administrator || user || elevationChild) && (sub === 'status' || args.flags.status)) {
process.stderr.write('daemon: privilege flags apply only to start, stop, or restart\n')
return 1
}
if (user && sub !== 'start' && sub !== 'restart') {
process.stderr.write('daemon: --user applies only to start or restart\n')
return 1
}
if (elevationChild && currentProcessIdentity().privilege !== 'administrator') {
process.stderr.write('daemon: internal elevation helper did not receive an Administrator token\n')
return 1
}
if (administrator && !elevationChild && currentProcessIdentity().privilege !== 'administrator') {
if (sub !== 'start' && sub !== 'stop' && sub !== 'restart') {
process.stderr.write('daemon: --administrator requires start, stop, or restart\n')
return 1
}
return runElevatedDaemonLifecycle(args, sub)
}
if (args.flags.status || sub === 'status') {
return printDaemonStatus(args)
}
@@ -516,9 +697,16 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
return stopDaemon(args)
}
if (sub === 'restart') {
if (user) return restartDaemonAsUser(args)
return restartDaemon(args)
}
if (sub === 'start' || args.flags.detach) {
if (user && currentProcessIdentity().privilege === 'administrator') {
process.stderr.write(
'daemon: cannot launch a user daemon from an Administrator process; run this command from an unelevated terminal\n'
)
return 1
}
return startDetachedDaemon(args)
}
// Bare `daemon` (or `daemon run`) → foreground, the existing behavior below.
@@ -551,13 +739,46 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
}
}
// Keep the selected host as the policy/storage identity, while resolving
// its current network route independently. A v3 pair can therefore prefer
// WSS/Tailscale and fall back to LAN without creating duplicate hosts.
const configuredUrl = url
const configuredSession = await getSession(configuredUrl)
let useSessionHeader = false
let brokerRoute: import('../transport/BrokerRelaySocket.js').BrokerRouteConfig | undefined
let activeRoute = configuredSession?.routeCandidates?.find(candidate => candidate.relay.url === configuredUrl)?.role
?? (configuredSession?.routeCandidates?.length ? null : configuredSession?.endpointRole ?? inferEndpointRole(configuredUrl))
if (!resolveRemoteOrNull(args) && configuredSession?.routeCandidates?.length) {
const candidates = configuredSession.preferSecureRoutes
? secureFirstCandidates(configuredSession.routeCandidates)
: configuredSession.routeCandidates
try {
const route = await probeCandidatesByPriority(candidates, { sessionToken: configuredSession.token })
url = route.relay.url
useSessionHeader = route.role.toLowerCase() === 'plugin_proxy' && !route.broker
if (route.broker && route.proxy) {
if (!route.proxy.certificateDerBase64) throw new Error('Hermes Reach route is missing its paired certificate')
brokerRoute = { url: route.broker.url, hostId: route.broker.hostId, credentialKind: route.broker.credentialKind, token: route.broker.token, innerUrl: route.relay.url, innerPinSha256: route.proxy.pinSha256, innerCertificateDerBase64: route.proxy.certificateDerBase64 }
}
activeRoute = route.broker ? 'outbound_broker' : route.role
log.info({ event: 'route_selected', configured_url: configuredUrl, url, role: route.role })
} catch (e) {
log.warn({
event: 'route_probe_failed',
configured_url: configuredUrl,
message: e instanceof Error ? e.message : String(e),
fallback_url: configuredUrl
})
}
}
// Resolve credentials: daemon takes ONLY --token or stored session. No
// pairing code path (the daemon can't do the one-time code → token
// trade safely — the token should already be stored). No interactive
// fallback (headless).
const argToken = typeof args.flags.token === 'string' ? args.flags.token : undefined
const envToken = process.env.HERMES_RELAY_TOKEN
const stored = await getSession(url)
const stored = configuredSession ?? await getSession(url)
const token = argToken ?? envToken ?? stored?.token
if (!token) {
@@ -574,10 +795,8 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
// connectivity itself a privileged operation.
const consented = stored?.toolsConsented === true
const allowToolsFlag = !!args.flags['allow-tools']
const accessMode = effectiveHostAccessMode(
await getHostAccessMode(url),
stored?.toolsConsented === true
)
const storedAccessMode = await getHostAccessMode(configuredUrl)
const accessMode = effectiveHostAccessMode(storedAccessMode, stored?.toolsConsented === true)
const toolsEnabled = consented || allowToolsFlag || accessMode !== 'ask'
log.info({
@@ -598,6 +817,8 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
pid: process.pid,
process_name: path.basename(process.execPath),
url,
configured_url: configuredUrl,
active_route: activeRoute ?? undefined,
state: 'starting',
started_at: nowSec(),
updated_at: nowSec(),
@@ -618,6 +839,8 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
const relay = new RelayTransport({
url,
sessionToken: token,
sessionHeader: useSessionHeader,
broker: brokerRoute,
...desktopRelayIdentity()
})
@@ -678,14 +901,23 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
// or redirected daemon still fails host input closed because no visible
// local grant approval prompt can run.
const interactive = !!process.stdin.isTTY && !!process.stderr.isTTY
const capabilities = effectiveHostCapabilityPolicies(
storedAccessMode,
stored?.toolsConsented === true,
await getHostCapabilityPolicies(configuredUrl)
)
configureComputerUseRuntime({
url,
url: configuredUrl,
computerUseConsented: computerUseEnabled,
consentSource: consented ? 'stored' : toolsEnabled ? 'override' : 'none',
accessMode
accessMode,
capabilities
})
configureCapabilityPolicies(capabilities)
const usb = capabilities.usb !== 'disabled'
const adb = usb && adbBackendAvailable()
const advertisedTools = toolsEnabled
? advertisedDesktopTools({ computerUse: computerUseEnabled })
? advertisedDesktopTools({ computerUse: computerUseEnabled, capabilities, usb, adb })
: []
const toDaemonGrantStatus = (grant: ComputerGrant | null): DaemonComputerGrantStatus => ({
active: grant !== null,
@@ -722,7 +954,7 @@ export async function daemonCommand(args: ParsedArgs): Promise<number> {
consentGranted: true,
interactive,
hostUrl: url,
handlers: desktopHandlers({ computerUse: computerUseEnabled }),
handlers: desktopHandlers({ computerUse: computerUseEnabled, capabilities, usb, adb }),
advertisedTools: [...advertisedTools]
})
: null
@@ -839,6 +1071,9 @@ export default daemonCommand
export type { LogFields }
export {
daemonStatusIsReady as __daemonStatusIsReadyForTests,
buildDaemonChildArgs as __buildDaemonChildArgsForTests,
buildElevationLaunchPlan as __buildElevationLaunchPlanForTests,
quoteWindowsArgument as __quoteWindowsArgumentForTests,
makeLogger as __makeLoggerForTests,
readDetachedStartupFailure as __readDetachedStartupFailureForTests,
rpcErrorMessage as __rpcErrorMessageForTests,
+170 -23
View File
@@ -2,14 +2,25 @@ import type { ParsedArgs } from '../cli.js'
import { getActiveDesktopRelayUrl, getDesktopHostAliases, setActiveDesktopRelayUrl, setDesktopHostAlias } from '../desktopConfig.js'
import {
effectiveHostAccessMode,
effectiveHostCapabilityPolicies,
getHostCapabilityPolicies,
getHostAccessMode,
isHostAccessMode,
removeHostAccessPolicy,
setHostAccessMode,
setHostCapabilityPolicy,
HOST_CAPABILITIES,
CAPABILITY_ACCESS_MODES,
type CapabilityPolicies,
type HostCapability,
type HostAccessMode
} from '../lib/hostAccessPolicy.js'
import { theme as makeTheme } from '../lib/theme.js'
import { printUsage, type UsageSpec, unknownSubcommand } from '../lib/usage.js'
import { getSession, listSessions, saveSession } from '../remoteSessions.js'
import { deleteSession, getSession, listSessions, saveSession } from '../remoteSessions.js'
import { candidateDisplayLabel, displayLabel, inferEndpointRole } from '../endpoint.js'
import { probeCandidate, secureFirstCandidates } from '../pairingQr.js'
import { describeTransportSecurity } from '../transportSecurity.js'
const HOSTS_USAGE: UsageSpec = {
name: 'hosts',
@@ -18,23 +29,31 @@ const HOSTS_USAGE: UsageSpec = {
'hosts [list] [--json]',
'hosts select <relay-url>',
'hosts rename <relay-url> <name>',
'hosts access <ask|trusted|full-access> [--remote <url>] [--yes]'
'hosts test [--remote <relay-url>] [--json]',
'hosts forget <relay-url> --yes',
'hosts access <restricted|ask-every-time|standard|full-access> [--remote <url>] [--yes]',
'hosts capability <commands|files|screen-input|usb|microphone|camera> <disabled|ask|allow> [--remote <url>] [--yes]'
],
subcommands: [
{ verb: 'list', desc: 'List locally paired Hermes hosts (default)' },
{ verb: 'select <url>', desc: 'Choose the host used by the tray and daemon' },
{ verb: 'rename <url> <name>', desc: 'Set a local display name for a paired host' },
{ verb: 'access <mode>', desc: 'Set this PC access policy for one host' }
{ verb: 'test', desc: 'Test saved routes and report the best available connection' },
{ verb: 'forget <url>', desc: 'Remove the local pairing, alias, and access policy' },
{ verb: 'access <mode>', desc: 'Set a Restricted, Ask Every Time, Standard, or Full Access preset' },
{ verb: 'capability <name> <mode>', desc: 'Set one capability; exact presets are recognized automatically' }
],
flags: [
{ flag: '--remote <url>', desc: 'Host targeted by the access command' },
{ flag: '--json', desc: 'Emit machine-readable host state' },
{ flag: '--yes', desc: 'Confirm Full Access non-interactively' }
{ flag: '--yes', desc: 'Confirm Full Access, hardware Allow, or forgetting a host' }
],
examples: [
'hermes-relay hosts --json',
'hermes-relay hosts select wss://home.example:8767',
'hermes-relay hosts access full-access --remote wss://home.example:8767 --yes'
'hermes-relay hosts access ask-every-time --remote wss://home.example:8767',
'hermes-relay hosts access standard --remote wss://home.example:8767',
'hermes-relay hosts capability usb ask --remote wss://home.example:8767'
]
}
@@ -46,6 +65,8 @@ export interface LocalHostSummary {
paired_at: number
is_active: boolean
access_mode: HostAccessMode
capabilities: CapabilityPolicies
broker_configured: boolean
}
function hostLabel(url: string): string {
@@ -58,23 +79,37 @@ function hostLabel(url: string): string {
export function parseAccessMode(value: string | undefined): HostAccessMode | null {
const normalized = value?.trim().toLowerCase().replaceAll('-', '_')
return isHostAccessMode(normalized) ? normalized : null
if (normalized === 'restricted') return 'ask'
if (normalized === 'prompt' || normalized === 'ask_every_time') return 'ask_every_time'
if (normalized === 'standard') return 'structured'
return isHostAccessMode(normalized) && normalized !== 'custom' ? normalized : null
}
export function displayAccessMode(mode: HostAccessMode): string {
if (mode === 'ask') return 'restricted'
if (mode === 'ask_every_time') return 'ask-every-time'
if (mode === 'structured') return 'standard'
if (mode === 'trusted' || mode === 'custom') return 'custom'
return 'full-access'
}
async function localHosts(): Promise<LocalHostSummary[]> {
const [sessions, active, aliases] = await Promise.all([listSessions(), getActiveDesktopRelayUrl(), getDesktopHostAliases()])
return Promise.all(Object.entries(sessions).map(async ([url, session]) => ({
url,
host: aliases[url] ?? hostLabel(url),
server_version: session.serverVersion,
endpoint_role: session.endpointRole ?? null,
paired_at: session.pairedAt,
is_active: url === active,
access_mode: effectiveHostAccessMode(
await getHostAccessMode(url),
session.toolsConsented === true
)
}))).then(hosts => hosts.sort((a, b) =>
return Promise.all(Object.entries(sessions).map(async ([url, session]) => {
const storedMode = await getHostAccessMode(url)
const legacyConsented = session.toolsConsented === true
return {
url,
host: aliases[url] ?? hostLabel(url),
server_version: session.serverVersion,
endpoint_role: session.endpointRole ?? inferEndpointRole(url),
paired_at: session.pairedAt,
is_active: url === active,
access_mode: effectiveHostAccessMode(storedMode, legacyConsented),
capabilities: effectiveHostCapabilityPolicies(storedMode, legacyConsented, await getHostCapabilityPolicies(url)),
broker_configured: session.routeCandidates?.some(candidate => ['outbound_broker', 'relay_broker', 'broker'].includes(candidate.role.toLowerCase())) ?? false
}
})).then(hosts => hosts.sort((a, b) =>
Number(b.is_active) - Number(a.is_active) || b.paired_at - a.paired_at || a.url.localeCompare(b.url)
))
}
@@ -110,13 +145,43 @@ async function listHosts(args: ParsedArgs): Promise<number> {
process.stdout.write(t.bold(`Paired Hermes hosts (${hosts.length})`) + '\n')
for (const host of hosts) {
process.stdout.write(
` ${host.is_active ? '*' : ' '} ${host.host} ${host.access_mode.replace('_', '-')}\n` +
t.muted(` ${host.url}${host.endpoint_role ? ` (${host.endpoint_role})` : ''}`) + '\n'
` ${host.is_active ? '*' : ' '} ${host.host} ${displayAccessMode(host.access_mode)}\n` +
t.muted(` ${host.url}${host.endpoint_role ? ` (${displayLabel(host.endpoint_role)})` : ''}`) + '\n' +
t.muted(` Commands: ${host.capabilities.commands} · Files: ${host.capabilities.files} · Screen/input: ${host.capabilities.screen_input} · USB: ${host.capabilities.usb}`) + '\n'
)
}
return 0
}
async function testHostRoutes(args: ParsedArgs): Promise<number> {
const requested = typeof args.flags.remote === 'string' ? args.flags.remote.trim() : ''
const url = requested || await getActiveDesktopRelayUrl() || ''
const session = url ? await getSession(url) : null
if (!url || !session) {
process.stderr.write('error: select or pass a locally paired Hermes host\n')
return 1
}
const candidates = secureFirstCandidates(session.routeCandidates?.length ? session.routeCandidates : [{
role: session.endpointRole ?? 'custom', priority: 0,
api: { host: new URL(url).hostname, port: Number(new URL(url).port || (url.startsWith('wss:') ? 443 : 80)), tls: url.startsWith('wss:') },
relay: { url }
}])
const results = await Promise.all(candidates.map(async candidate => {
const result = await probeCandidate(candidate, AbortSignal.timeout(5_000), session.token)
const security = describeTransportSecurity(candidate.relay.url, candidate.role)
return { role: candidate.role, label: candidateDisplayLabel(candidate), url: candidate.broker?.url ?? candidate.relay.url, reachable: result.reachable, elapsed_ms: result.elapsedMs, encrypted: security.encrypted, security: candidate.broker ? 'Reachability only; inner Secure Link verifies on connect' : security.label, error: result.error ?? null }
}))
const best = results.find(result => result.reachable) ?? null
if (args.flags.json) process.stdout.write(JSON.stringify({ ok: best !== null, host_url: url, best, routes: results }, null, 2) + '\n')
else {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
process.stdout.write(t.bold('Hermes connection test') + '\n')
for (const result of results) process.stdout.write(` ${result.reachable ? t.ok('●') : t.err('●')} ${result.label} ${result.security} ${result.reachable ? `${result.elapsed_ms}ms` : result.error ?? 'unreachable'}\n`)
process.stdout.write(best ? t.okLine(`Best route: ${best.label}`) + '\n' : t.errLine('No saved route is reachable.') + '\n')
}
return best ? 0 : 1
}
async function selectHost(args: ParsedArgs): Promise<number> {
const url = args.positional[0]?.trim()
if (!url) {
@@ -136,7 +201,7 @@ async function selectHost(args: ParsedArgs): Promise<number> {
async function setAccess(args: ParsedArgs): Promise<number> {
const mode = parseAccessMode(args.positional[0])
if (!mode) {
process.stderr.write('error: access mode must be ask, trusted, or full-access\n')
process.stderr.write('error: access mode must be restricted, ask-every-time, standard, or full-access\n')
return 2
}
const requested = typeof args.flags.remote === 'string' ? args.flags.remote.trim() : ''
@@ -148,7 +213,7 @@ async function setAccess(args: ParsedArgs): Promise<number> {
}
if (mode === 'full_access' && args.flags.yes !== true) {
process.stderr.write(
'error: Full Access allows this host to use commands, files, screen, keyboard, and mouse without task grants. Pass --yes to confirm.\n'
'error: Full Access allows every available capability, including commands, files, screen, input, and Raw USB, without task grants. Pass --yes to confirm.\n'
)
return 2
}
@@ -167,12 +232,91 @@ async function setAccess(args: ParsedArgs): Promise<number> {
if (args.flags.json) process.stdout.write(JSON.stringify(payload, null, 2) + '\n')
else {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
process.stdout.write(t.okLine(`${hostLabel(url)} access set to ${mode.replace('_', '-')}`) + '\n')
process.stdout.write(t.okLine(`${hostLabel(url)} access set to ${displayAccessMode(mode)}`) + '\n')
process.stdout.write(t.muted('Restart the daemon to apply this policy.') + '\n')
}
return 0
}
async function setCapability(args: ParsedArgs): Promise<number> {
const capability = args.positional[0]?.trim().toLowerCase()
const mode = args.positional[1]?.trim().toLowerCase()
const normalizedCapability = capability?.replaceAll('-', '_') as HostCapability | undefined
if (!normalizedCapability || !HOST_CAPABILITIES.includes(normalizedCapability)) {
process.stderr.write('error: capability must be commands, files, screen-input, usb, microphone, or camera\n')
return 2
}
if (!CAPABILITY_ACCESS_MODES.includes(mode as typeof CAPABILITY_ACCESS_MODES[number])) {
process.stderr.write('error: capability mode must be disabled, ask, or allow\n')
return 2
}
if ((normalizedCapability === 'microphone' || normalizedCapability === 'camera') && mode !== 'disabled') {
process.stderr.write(`error: ${normalizedCapability} brokering is not available yet; leave it disabled\n`)
return 2
}
if (mode === 'allow' && args.flags.yes !== true) {
process.stderr.write(`error: allowing ${normalizedCapability.replace('_', '/')} lets this host use that capability without per-operation approval. Pass --yes to confirm.\n`)
return 2
}
const requested = typeof args.flags.remote === 'string' ? args.flags.remote.trim() : ''
const url = requested || await getActiveDesktopRelayUrl() || ''
const session = url ? await getSession(url) : null
if (!url || !session) {
process.stderr.write('error: select or pass a locally paired Hermes host\n')
return 1
}
const policy = await setHostCapabilityPolicy(
url,
normalizedCapability,
mode as typeof CAPABILITY_ACCESS_MODES[number]
)
await saveSession(url, session.token, session.serverVersion, {
pairedAt: session.pairedAt,
toolsConsented: Object.values(policy.capabilities).some(value => value !== 'disabled')
})
const payload = { ok: true, url, access_mode: policy.access_mode, capability: normalizedCapability, mode, capabilities: policy.capabilities, restart_required: true }
if (args.flags.json) process.stdout.write(JSON.stringify(payload, null, 2) + '\n')
else {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
const label = normalizedCapability === 'usb' ? 'Raw USB' : normalizedCapability.replace('_', '/')
process.stdout.write(t.okLine(`${hostLabel(url)} ${label} access set to ${mode} (${displayAccessMode(policy.access_mode)})`) + '\n')
process.stdout.write(t.muted('Restart the daemon to apply this policy.') + '\n')
}
return 0
}
async function forgetHost(args: ParsedArgs): Promise<number> {
const url = args.positional[0]?.trim() ?? ''
if (!url || !(await getSession(url))) {
process.stderr.write('error: `hosts forget` requires a locally paired relay URL\n')
return 1
}
if (args.flags.yes !== true) {
process.stderr.write('error: forgetting a host removes its local session, display name, and access policy. Pass --yes to confirm.\n')
return 2
}
const active = await getActiveDesktopRelayUrl()
await Promise.all([
deleteSession(url),
removeHostAccessPolicy(url),
setDesktopHostAlias(url, null)
])
let nextActive = active
if (active === url) {
const remaining = Object.keys(await listSessions()).sort()
nextActive = remaining[0] ?? null
await setActiveDesktopRelayUrl(nextActive)
}
const payload = { ok: true, forgotten_url: url, active_url: nextActive, restart_required: active === url }
if (args.flags.json) process.stdout.write(JSON.stringify(payload, null, 2) + '\n')
else {
const t = makeTheme({ noColor: !!args.flags['no-color'] })
process.stdout.write(t.okLine(`forgot host ${hostLabel(url)}`) + '\n')
if (active === url) process.stdout.write(t.muted(nextActive ? `Selected ${hostLabel(nextActive)} as the active host.` : 'No active host remains.') + '\n')
}
return 0
}
export async function hostsCommand(args: ParsedArgs): Promise<number> {
if (args.flags.help) {
printUsage(HOSTS_USAGE, makeTheme({ noColor: !!args.flags['no-color'] }))
@@ -182,7 +326,10 @@ export async function hostsCommand(args: ParsedArgs): Promise<number> {
if (subcommand === 'list') return listHosts(args)
if (subcommand === 'select') return selectHost(args)
if (subcommand === 'rename') return renameHost(args)
if (subcommand === 'test') return testHostRoutes(args)
if (subcommand === 'forget') return forgetHost(args)
if (subcommand === 'access') return setAccess(args)
if (subcommand === 'capability') return setCapability(args)
return unknownSubcommand(HOSTS_USAGE, subcommand, makeTheme({ noColor: !!args.flags['no-color'] }))
}
+58 -11
View File
@@ -24,12 +24,15 @@ import {
import {
payloadToRelayCandidates,
probeCandidatesByPriority,
relayPairingCodeFromPayload
relayPairingCodeFromPayload,
secureFirstCandidates
} from '../pairingQr.js'
import { DEFAULT_RELAY_PORT, normalizeRelayUrl, resolveFirstRunUrl } from '../relayUrlPrompt.js'
import { saveSession } from '../remoteSessions.js'
import { ensureToolsConsent } from '../tools/consent.js'
import { RelayTransport } from '../transport/RelayTransport.js'
import { candidateDisplayLabel, displayLabel, inferEndpointRole } from '../endpoint.js'
import type { BrokerRouteConfig } from '../transport/BrokerRelaySocket.js'
const PAIR_USAGE: UsageSpec = {
name: 'pair',
@@ -41,6 +44,7 @@ const PAIR_USAGE: UsageSpec = {
desc: 'Paste a full QR payload or hermes-relay://pair invite (recommended — probes endpoints)'
},
{ flag: '--remote <url>', desc: 'Relay URL (with [CODE] or an interactive prompt)' },
{ flag: '--prefer-direct', desc: 'Respect invite order instead of preferring secure routes' },
{ flag: '--code <code>', desc: '6-char pairing code (or pass it as the positional arg)' },
{
flag: '--grant-tools',
@@ -73,6 +77,27 @@ interface PairTarget {
code: string
/** Active-endpoint role if this came from a multi-endpoint QR probe. */
endpointRole: string | null
routeCandidates?: ReturnType<typeof payloadToRelayCandidates>
preferSecureRoutes?: boolean
certPin?: string
broker?: BrokerRouteConfig
}
export function rankPairingCandidates(candidates: ReturnType<typeof payloadToRelayCandidates>, preferSecure: boolean) {
return preferSecure ? secureFirstCandidates(candidates) : candidates
}
export function brokerRouteForCandidate(candidate: ReturnType<typeof payloadToRelayCandidates>[number]): BrokerRouteConfig | undefined {
if (!candidate.broker || !candidate.proxy?.certificateDerBase64) return undefined
return {
url: candidate.broker.url,
hostId: candidate.broker.hostId,
credentialKind: candidate.broker.credentialKind,
token: candidate.broker.token,
innerUrl: candidate.relay.url,
innerPinSha256: candidate.proxy.pinSha256,
innerCertificateDerBase64: candidate.proxy.certificateDerBase64,
}
}
async function resolvePairTarget(args: ParsedArgs): Promise<PairTarget | { error: string }> {
@@ -97,12 +122,17 @@ async function resolvePairTarget(args: ParsedArgs): Promise<PairTarget | { error
return { error: e instanceof Error ? e.message : String(e) }
}
const t = makeTheme({ noColor: !!args.flags['no-color'] })
const preferSecure = args.flags['prefer-direct'] !== true
process.stderr.write(t.bold(`Probing ${candidates.length} endpoint(s)…`) + '\n')
let winner
try {
winner = await probeCandidatesByPriority(candidates, {
// Hermes Secure Link tunnels the normal first pairing-code frame. The
// QR pin is the operator trust ceremony, so secure-only invites can
// bootstrap without falling back to a plain/direct route.
const rankedCandidates = rankPairingCandidates(candidates, preferSecure)
winner = await probeCandidatesByPriority(rankedCandidates, {
onProbe: (ev) => {
const label = `[${ev.index}/${ev.total}] ${ev.candidate.role} ${ev.candidate.relay.url}`
const label = `[${ev.index}/${ev.total}] ${candidateDisplayLabel(ev.candidate)} ${ev.candidate.relay.url}`
if (ev.phase === 'result' && ev.reachable) {
process.stderr.write(` ${t.okLine(label)} ${t.muted(`${ev.elapsedMs}ms`)}\n`)
} else if (ev.phase === 'result') {
@@ -116,12 +146,17 @@ async function resolvePairTarget(args: ParsedArgs): Promise<PairTarget | { error
return { error: `no endpoints reachable: ${e instanceof Error ? e.message : String(e)}` }
}
process.stderr.write(
` ${t.cyan(SYMBOLS.arrow)} picked ${t.bold(winner.role)} endpoint ${winner.relay.url}\n`
` ${t.cyan(SYMBOLS.arrow)} picked ${t.bold(candidateDisplayLabel(winner))} endpoint ${winner.relay.url}\n`
)
const broker = brokerRouteForCandidate(winner)
return {
url: winner.relay.url,
code: pairingCode,
endpointRole: winner.role
endpointRole: winner.role,
routeCandidates: candidates,
preferSecureRoutes: preferSecure,
certPin: winner.proxy?.pinSha256,
...(broker ? { broker } : {})
}
}
@@ -163,7 +198,7 @@ async function resolvePairTarget(args: ParsedArgs): Promise<PairTarget | { error
return { error: e instanceof Error ? e.message : String(e) }
}
}
return { url, code, endpointRole: null }
return { url, code, endpointRole: inferEndpointRole(url) }
}
export async function pairCommand(args: ParsedArgs): Promise<number> {
@@ -192,6 +227,8 @@ export async function pairCommand(args: ParsedArgs): Promise<number> {
const relay = new RelayTransport({
url: target.url,
pairingCode: target.code,
expectedCertPin: target.certPin,
broker: target.broker,
...desktopRelayIdentity()
})
@@ -199,6 +236,12 @@ export async function pairCommand(args: ParsedArgs): Promise<number> {
const outcome = await relay.whenAuthResolved()
if (outcome.ok) {
const persistedRoutes = target.routeCandidates?.flatMap(candidate => {
if (!candidate.broker) return candidate
const durable = outcome.meta.routeCredential
if (!durable) return []
return { ...candidate, broker: { ...candidate.broker, url: durable.brokerUrl, hostId: durable.hostId, credentialKind: 'route' as const, token: durable.token, expiresAt: durable.expiresAt } }
})
// Fold --auto-grant-tools into the initial save so the consent flag and
// the token land atomically. The interactive --grant-tools path runs
// ensureToolsConsent() below, which writes its own follow-up save.
@@ -206,13 +249,20 @@ export async function pairCommand(args: ParsedArgs): Promise<number> {
grants: outcome.meta.grants,
ttlExpiresAt: outcome.meta.ttlExpiresAt,
endpointRole: target.endpointRole,
routeCandidates: persistedRoutes,
preferSecureRoutes: target.preferSecureRoutes,
certPin: target.certPin,
initializeAccessPolicy: true,
...(autoGrant ? { toolsConsented: true } : {})
})
process.stdout.write(t.okLine('Paired. Token stored in ~/.hermes/remote-sessions.json') + '\n')
process.stdout.write(t.muted(` server: ${outcome.serverVersion ?? '?'}`) + '\n')
process.stdout.write(t.muted(` relay: ${target.url}`) + '\n')
if (target.endpointRole) {
process.stdout.write(t.muted(` route: ${target.endpointRole}`) + '\n')
process.stdout.write(t.muted(` route: ${target.broker ? 'Hermes Reach (experimental)' : displayLabel(target.endpointRole)}`) + '\n')
if (target.broker) {
process.stdout.write(t.warnLine('Experimental route selected; Tailscale or a direct TLS route is recommended for normal use.') + '\n')
}
}
if (autoGrant) {
@@ -228,11 +278,8 @@ export async function pairCommand(args: ParsedArgs): Promise<number> {
)
}
} else {
// Nudge the daemon-first workflow: most users who pair from a terminal
// want desktop tools, and discovering --grant-tools after the fact means
// an extra `shell` round-trip. Surface it once, here.
process.stdout.write(
t.muted(' tip: add --grant-tools to also enable desktop tools (needed for `daemon`).') + '\n'
t.muted(' desktop access: Ask Every Time (start `daemon`; each operation requires local approval).') + '\n'
)
}
+15 -3
View File
@@ -72,6 +72,9 @@ import {
shouldAdvertiseComputerUse
} from '../tools/handlerSet.js'
import { DesktopToolRouter } from '../tools/router.js'
import { effectiveHostAccessMode, effectiveHostCapabilityPolicies, getHostAccessMode, getHostCapabilityPolicies } from '../lib/hostAccessPolicy.js'
import { configureCapabilityPolicies } from '../tools/capabilityRuntime.js'
import { adbBackendAvailable } from '../tools/handlers/adb.js'
import { RelayTransport } from '../transport/RelayTransport.js'
const ATTACH_TIMEOUT_MS = 30_000
@@ -152,6 +155,7 @@ export async function connectAndAuth(args: ParsedArgs): Promise<AuthedRelay> {
const relay = new RelayTransport(cfg)
relay.onAuthSuccess((token, ver, meta) => {
void saveSession(url, token, ver, {
initializeAccessPolicy: true,
grants: meta.grants,
ttlExpiresAt: meta.ttlExpiresAt,
endpointRole
@@ -410,16 +414,24 @@ export async function shellCommand(args: ParsedArgs): Promise<number> {
const consent = await ensureToolsConsent(url)
if (consent.consented) {
const computerUseEnabled = shouldAdvertiseComputerUse(args.flags)
const storedAccessMode = await getHostAccessMode(url)
const accessMode = effectiveHostAccessMode(storedAccessMode, consent.consented)
const capabilities = effectiveHostCapabilityPolicies(storedAccessMode, consent.consented, await getHostCapabilityPolicies(url))
configureCapabilityPolicies(capabilities)
const usb = capabilities.usb !== 'disabled'
const adb = usb && adbBackendAvailable()
configureComputerUseRuntime({
url,
computerUseConsented: computerUseEnabled,
consentSource: consent.source ?? 'stored'
consentSource: consent.source ?? 'stored',
accessMode,
capabilities
})
const advertisedTools = advertisedDesktopTools({ computerUse: computerUseEnabled })
const advertisedTools = advertisedDesktopTools({ computerUse: computerUseEnabled, capabilities, usb, adb })
toolRouter = new DesktopToolRouter({
consentGranted: true,
hostUrl: url,
handlers: desktopHandlers({ computerUse: computerUseEnabled }),
handlers: desktopHandlers({ computerUse: computerUseEnabled, capabilities, usb, adb }),
advertisedTools: [...advertisedTools]
})
toolRouter.attach(relay)
+4 -3
View File
@@ -9,6 +9,7 @@ import type { ParsedArgs } from '../cli.js'
import { theme as makeTheme } from '../lib/theme.js'
import { printUsage, type UsageSpec } from '../lib/usage.js'
import { listSessions, type RemoteSessionRecord } from '../remoteSessions.js'
import { displayLabel } from '../endpoint.js'
const STATUS_USAGE: UsageSpec = {
name: 'status',
@@ -60,7 +61,7 @@ export async function statusCommand(args: ParsedArgs): Promise<number> {
: Object.fromEntries(
Object.entries(sessions).map(([url, rec]) => [
url,
{ ...rec, token: '(redacted)' }
{ ...rec, token: '(redacted)', routeCandidates: rec.routeCandidates?.map(candidate => candidate.broker ? { ...candidate, broker: { ...candidate.broker, token: '(redacted)' } } : candidate) }
])
)
process.stdout.write(JSON.stringify(out, null, 2) + '\n')
@@ -93,8 +94,8 @@ export async function statusCommand(args: ParsedArgs): Promise<number> {
kv('desktop', `${t.statusDot(!!rec.toolsConsented)} tools=${rec.toolsConsented ? 'yes' : 'no'}, computer-use=${computerUse}`) + '\n'
)
const role = parseRole(rec.endpointRole)
if (role) {
process.stdout.write(kv('route', roleLabel(role)) + '\n')
if (rec.endpointRole) {
process.stdout.write(kv('route', role ? roleLabel(role) : displayLabel(rec.endpointRole)) + '\n')
}
if (rec.grants && Object.keys(rec.grants).length > 0) {
const formatted = Object.entries(rec.grants)
+1
View File
@@ -114,6 +114,7 @@ export async function toolsCommand(args: ParsedArgs): Promise<number> {
const relay = new RelayTransport(relayCfg)
relay.onAuthSuccess((token, ver, meta) => {
void saveSession(url, token, ver, {
initializeAccessPolicy: true,
grants: meta.grants,
ttlExpiresAt: meta.ttlExpiresAt,
endpointRole
+1
View File
@@ -400,6 +400,7 @@ async function connectAndAuth(args: ParsedArgs): Promise<AuthedRelay> {
relay.onAuthSuccess((token, ver, meta) => {
mintedToken = token
void saveSession(url, token, ver, {
initializeAccessPolicy: true,
grants: meta.grants,
ttlExpiresAt: meta.ttlExpiresAt,
endpointRole
+66 -3
View File
@@ -1,5 +1,66 @@
import { execFileSync } from 'node:child_process'
import { hostname, machine, release, type } from 'node:os'
import { randomUUID } from 'node:crypto'
import {
chmodSync,
mkdirSync,
readFileSync,
renameSync,
unlinkSync,
writeFileSync
} from 'node:fs'
import { homedir, hostname, machine, release, type } from 'node:os'
import { dirname, join } from 'node:path'
const DEVICE_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const defaultDeviceIdPath = () => join(homedir(), '.hermes', 'desktop-device-id')
function readDeviceId(path: string): string | null {
try {
const value = readFileSync(path, 'utf8').trim()
return DEVICE_ID_PATTERN.test(value) ? value.toLowerCase() : null
} catch {
return null
}
}
/** Stable private identity for one desktop CLI installation.
*
* Hostname and model are display metadata; they are not ownership keys. A
* random per-install UUID lets several PCs pair to the same relay without one
* PC's explicit re-pair revoking another PC's session. */
export function desktopDeviceId(path = defaultDeviceIdPath()): string {
const existing = readDeviceId(path)
if (existing) return existing
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
const generated = randomUUID().toLowerCase()
try {
// Exclusive creation makes simultaneous first launches converge on the
// same stored identity instead of returning two different UUIDs.
writeFileSync(path, `${generated}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 })
return generated
} catch {
const raced = readDeviceId(path)
if (raced) return raced
// Repair a malformed legacy/partial file atomically.
const temporary = `${path}.tmp-${process.pid}-${Date.now()}`
try {
writeFileSync(temporary, `${generated}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 })
renameSync(temporary, path)
chmodSync(path, 0o600)
return generated
} finally {
try {
unlinkSync(temporary)
} catch {
// rename consumed it, or creation failed before it existed
}
}
}
}
function windowsDeviceModel(): string | null {
if (process.platform !== 'win32') return null
@@ -26,13 +87,14 @@ function windowsDeviceModel(): string | null {
}
/** Consistent identity metadata for every desktop relay connection surface. */
export function desktopRelayIdentity(): {
export function desktopRelayIdentity(deviceIdPath?: string): {
deviceName: string
deviceHostname: string
deviceModel: string
devicePlatform: string
clientSurface: string
deviceFormFactor: string
deviceId: string
} {
const host = hostname().trim() || 'Hermes-Relay desktop'
return {
@@ -41,6 +103,7 @@ export function desktopRelayIdentity(): {
deviceModel: windowsDeviceModel() || machine() || process.arch,
devicePlatform: `${type()} ${release()}`.trim(),
clientSurface: 'desktop',
deviceFormFactor: 'desktop'
deviceFormFactor: 'desktop',
deviceId: desktopDeviceId(deviceIdPath)
}
}
+64
View File
@@ -57,6 +57,37 @@ export interface EndpointCandidate {
priority: number
api: ApiEndpoint
relay: RelayEndpoint
/** Native plugin secure-proxy advertisement. Preserved even when the
* desktop currently consumes only its relay WSS path. */
proxy?: {
url: string
transportHint?: string
pinSha256: string
certificateDerBase64?: string
surfaces?: string[]
}
security?: string
recommended?: boolean
/** Experimental routes are supported for explicit evaluation but are
* never presented as the default remote-access recommendation. */
experimental?: boolean
broker?: {
url: string
hostId: string
credentialKind: 'bootstrap' | 'route'
token: string
expiresAt?: string | number | null
}
}
export function candidateDisplayLabel(candidate: Pick<EndpointCandidate, 'role' | 'broker'> & Partial<Pick<EndpointCandidate, 'relay'>>): string {
const role = candidate.role.toLowerCase()
if (candidate.broker && (role === 'outbound_broker' || role === 'broker' || role === 'relay_broker')) return 'Hermes Reach (experimental)'
// Older session files used the generic `custom` role even for ordinary
// private-address routes. Keep named operator-defined roles intact, but
// classify that legacy placeholder from its actual relay URL.
if (role === 'custom' && candidate.relay?.url) return displayLabel(inferEndpointRole(candidate.relay.url))
return displayLabel(candidate.role)
}
/**
@@ -96,6 +127,9 @@ export function isKnownRole(role: string): boolean {
* exactly what they labeled it.
*/
export function displayLabel(role: string): string {
const normalized = role.toLowerCase()
if (normalized === 'plugin_proxy') return 'Hermes Secure Link'
if (normalized === 'outbound_broker' || normalized === 'relay_broker' || normalized === 'broker') return 'Hermes Reach (experimental)'
switch (parseRawRole(role)) {
case 'lan':
return 'LAN'
@@ -108,6 +142,36 @@ export function displayLabel(role: string): string {
}
}
/** Infer a built-in role for legacy/direct sessions that did not persist one. */
export function inferEndpointRole(rawUrl: string): EndpointRole {
try {
const parsed = new URL(rawUrl)
const host = parsed.hostname.replace(/^\[|\]$/g, '').toLowerCase()
const octets = host.split('.').map(Number)
const ipv4 = octets.length === 4 && octets.every(part => Number.isInteger(part) && part >= 0 && part <= 255)
if (host.endsWith('.ts.net') || (ipv4 && octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127)) {
return 'tailscale'
}
if (
host === 'localhost' || host.endsWith('.local') || host === '::1' ||
host.startsWith('fc') || host.startsWith('fd') ||
/^(fe8|fe9|fea|feb)/.test(host) ||
(ipv4 && (
octets[0] === 10 || octets[0] === 127 ||
(octets[0] === 169 && octets[1] === 254) ||
(octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) ||
(octets[0] === 192 && octets[1] === 168)
))
) {
return 'lan'
}
return 'public'
} catch {
return 'custom'
}
}
/**
* Type guard — is this value shaped like an `ApiEndpoint`? Used by the
* pairing parser to filter malformed candidates without throwing.
+72 -2
View File
@@ -31,15 +31,27 @@ export interface AuditEntry {
exit_code?: number
/** Truncated preview of the call args, for context. */
args_preview?: string
/** Bounded, redacted request detail for the local activity drilldown. */
request_detail?: string
/** Bounded command streams when returned by the handler. */
stdout?: string
stderr?: string
/** Bounded structured result after stdout/stderr are removed. */
result_detail?: string
request_truncated?: boolean
stdout_truncated?: boolean
stderr_truncated?: boolean
result_truncated?: boolean
/** Short success summary (path / exit code / first stdout line). */
summary?: string
error?: string
}
export type AuditCategory = 'command' | 'files' | 'screen' | 'input' | 'system' | 'other'
export type AuditCategory = 'command' | 'files' | 'screen' | 'input' | 'devices' | 'system' | 'other'
/** Rotate the log once it crosses ~1 MB, keeping a single `.1` backup. */
const MAX_BYTES = 1_000_000
const MAX_DETAIL_BYTES = 32_768
export function auditLogPath(): string {
return join(homedir(), '.hermes', 'desktop-audit.jsonl')
@@ -86,7 +98,7 @@ export async function readRecentAudit(limit = 50): Promise<AuditEntry[]> {
export function previewArgs(args: Record<string, unknown>): string | undefined {
try {
const parts: string[] = []
for (const key of ['path', 'command', 'cmd', 'pattern', 'cwd', 'pid', 'port', 'name']) {
for (const key of ['serial', 'source', 'destination', 'apk', 'path', 'command', 'script', 'executable', 'cmd', 'pattern', 'cwd', 'pid', 'port', 'name']) {
const v = (args as Record<string, unknown>)[key]
if (v !== undefined && v !== null && typeof v !== 'object') {
parts.push(`${key}=${String(v)}`)
@@ -102,6 +114,63 @@ export function previewArgs(args: Record<string, unknown>): string | undefined {
}
}
function boundedText(value: string): { text: string; truncated: boolean } {
const bytes = Buffer.from(value, 'utf8')
if (bytes.length <= MAX_DETAIL_BYTES) return { text: value, truncated: false }
return {
text: `${bytes.subarray(0, MAX_DETAIL_BYTES).toString('utf8')}\n[… truncated locally at ${MAX_DETAIL_BYTES} bytes]`,
truncated: true
}
}
/** Preserve useful local drilldown evidence without logging secrets, file
* bodies, environment values, or unbounded process output. */
export function auditDetails(
args: Record<string, unknown>,
result?: unknown
): Pick<AuditEntry, 'request_detail' | 'stdout' | 'stderr' | 'result_detail' | 'request_truncated' | 'stdout_truncated' | 'stderr_truncated' | 'result_truncated'> {
const safeRequest: Record<string, unknown> = {}
for (const key of [
'command', 'script', 'executable', 'arguments', 'cwd', 'path', 'source', 'destination',
'pattern', 'serial', 'apk', 'pid', 'port', 'job_id', 'offset', 'limit', 'timeout', 'reason'
]) {
if (args[key] !== undefined) safeRequest[key] = args[key]
}
const request = boundedText(JSON.stringify(safeRequest, null, 2))
const details: Pick<AuditEntry, 'request_detail' | 'stdout' | 'stderr' | 'result_detail' | 'request_truncated' | 'stdout_truncated' | 'stderr_truncated' | 'result_truncated'> = {
request_detail: request.text,
request_truncated: request.truncated || undefined
}
if (!result || typeof result !== 'object') {
if (result !== undefined) {
const value = boundedText(String(result))
details.result_detail = value.text
details.result_truncated = value.truncated || undefined
}
return details
}
const record = { ...(result as Record<string, unknown>) }
if (typeof record.stdout === 'string') {
const value = boundedText(record.stdout)
details.stdout = value.text
details.stdout_truncated = value.truncated || undefined
delete record.stdout
}
if (typeof record.stderr === 'string') {
const value = boundedText(record.stderr)
details.stderr = value.text
details.stderr_truncated = value.truncated || undefined
delete record.stderr
}
const serialized = JSON.stringify(record, null, 2)
if (serialized !== '{}') {
const value = boundedText(serialized)
details.result_detail = value.text
details.result_truncated = value.truncated || undefined
}
return details
}
/** Best-effort short success summary from a handler result. */
export function summarizeResult(result: unknown): string | undefined {
if (result === null || typeof result !== 'object') {
@@ -133,6 +202,7 @@ export function resultExitCode(result: unknown): number | undefined {
/** A small stable taxonomy shared by CLI audit consumers and the tray UI. */
export function categorizeTool(tool: string): AuditCategory {
const value = tool.toLowerCase()
if (value.includes('adb') || value.includes('usb')) return 'devices'
if (value.includes('computer_screenshot') || value.includes('screen')) return 'screen'
if (value.includes('computer_') || value.includes('mouse') || value.includes('keyboard')) return 'input'
if (value.includes('file') || value.includes('directory') || value.includes('patch')) return 'files'
+4
View File
@@ -30,6 +30,10 @@ export interface DaemonStatus {
* before status/stop treats an unrelated process as Hermes Relay. */
process_name?: string
url: string
/** Logical host selected by the user when `url` is a resolved fallback route. */
configured_url?: string
/** Wire route role selected for the current connection. */
active_route?: string
state: DaemonState
/** Epoch seconds. */
started_at: number
+173 -8
View File
@@ -2,21 +2,66 @@ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
export const HOST_ACCESS_MODES = ['ask', 'trusted', 'full_access'] as const
export const HOST_ACCESS_MODES = ['ask', 'ask_every_time', 'structured', 'trusted', 'full_access', 'custom'] as const
export const DESKTOP_CAPABILITIES = ['commands', 'files', 'screen_input'] as const
export const HARDWARE_CAPABILITIES = ['usb', 'microphone', 'camera'] as const
export const HOST_CAPABILITIES = [...DESKTOP_CAPABILITIES, ...HARDWARE_CAPABILITIES] as const
export const CAPABILITY_ACCESS_MODES = ['disabled', 'ask', 'allow'] as const
export type HostAccessMode = (typeof HOST_ACCESS_MODES)[number]
export type DesktopCapability = (typeof DESKTOP_CAPABILITIES)[number]
export type HardwareCapability = (typeof HARDWARE_CAPABILITIES)[number]
export type HostCapability = (typeof HOST_CAPABILITIES)[number]
export type CapabilityAccessMode = (typeof CAPABILITY_ACCESS_MODES)[number]
export type CapabilityPolicies = Record<HostCapability, CapabilityAccessMode>
export interface HostAccessPolicy {
access_mode: HostAccessMode
capabilities: CapabilityPolicies
updated_at?: string
}
export interface HostAccessPolicyFile {
version: 1
version: 2
hosts: Record<string, HostAccessPolicy>
}
const STORE_VERSION = 1 as const
const STORE_VERSION = 2 as const
export const DEFAULT_CAPABILITY_POLICIES: CapabilityPolicies = Object.freeze({
commands: 'disabled',
files: 'disabled',
screen_input: 'disabled',
usb: 'disabled',
microphone: 'disabled',
camera: 'disabled'
})
type PresetAccessMode = Exclude<HostAccessMode, 'custom'>
export const PRESET_CAPABILITY_POLICIES: Readonly<Record<PresetAccessMode, CapabilityPolicies>> = Object.freeze({
ask: Object.freeze({ ...DEFAULT_CAPABILITY_POLICIES }),
ask_every_time: Object.freeze({
commands: 'ask', files: 'ask', screen_input: 'ask', usb: 'ask', microphone: 'disabled', camera: 'disabled'
}),
structured: Object.freeze({
commands: 'disabled', files: 'allow', screen_input: 'ask', usb: 'ask', microphone: 'disabled', camera: 'disabled'
}),
trusted: Object.freeze({
commands: 'allow', files: 'allow', screen_input: 'ask', usb: 'ask', microphone: 'disabled', camera: 'disabled'
}),
full_access: Object.freeze({
commands: 'allow', files: 'allow', screen_input: 'allow', usb: 'allow', microphone: 'allow', camera: 'allow'
})
})
export function presetCapabilityPolicies(mode: HostAccessMode): CapabilityPolicies {
return { ...(mode === 'custom' ? DEFAULT_CAPABILITY_POLICIES : PRESET_CAPABILITY_POLICIES[mode]) }
}
function sameCapabilities(left: CapabilityPolicies, right: CapabilityPolicies): boolean {
return HOST_CAPABILITIES.every(capability => left[capability] === right[capability])
}
export function hostAccessPolicyPath(): string {
return process.env.HERMES_RELAY_HOST_ACCESS_POLICY_PATH ??
@@ -48,17 +93,39 @@ export function isHostAccessMode(value: unknown): value is HostAccessMode {
const emptyStore = (): HostAccessPolicyFile => ({ version: STORE_VERSION, hosts: {} })
const restrictiveness = (mode: HostAccessMode): number => HOST_ACCESS_MODES.indexOf(mode)
const capabilityRestrictiveness = (mode: CapabilityAccessMode): number => CAPABILITY_ACCESS_MODES.indexOf(mode)
function parsePolicy(value: unknown): HostAccessPolicy | null {
if (isHostAccessMode(value)) return { access_mode: value }
if (isHostAccessMode(value)) {
return { access_mode: value, capabilities: presetCapabilityPolicies(value) }
}
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
const raw = value as Record<string, unknown>
const mode = raw.access_mode ?? raw.mode
if (!isHostAccessMode(mode)) return null
const rawCapabilities = raw.capabilities && typeof raw.capabilities === 'object' && !Array.isArray(raw.capabilities)
? raw.capabilities as Record<string, unknown>
: {}
const capabilities = presetCapabilityPolicies(mode)
let hasExplicitCapabilities = false
for (const capability of HOST_CAPABILITIES) {
const value = rawCapabilities[capability]
if (typeof value === 'string' && CAPABILITY_ACCESS_MODES.includes(value as CapabilityAccessMode)) {
capabilities[capability] = value as CapabilityAccessMode
hasExplicitCapabilities = true
}
}
// Full Access is intentionally a real override. Older stores could retain
// an independent USB Ask value, which was misleading because unrestricted
// commands could already reach that hardware.
if (mode === 'full_access') Object.assign(capabilities, PRESET_CAPABILITY_POLICIES.full_access)
const normalizedMode = mode !== 'custom' && hasExplicitCapabilities && !sameCapabilities(capabilities, PRESET_CAPABILITY_POLICIES[mode])
? 'custom'
: mode
return {
access_mode: mode,
access_mode: normalizedMode,
capabilities,
updated_at: typeof raw.updated_at === 'string' ? raw.updated_at : undefined
}
}
@@ -72,9 +139,28 @@ function mergePolicy(
if (!url) return
const current = hosts[url]
if (!current || restrictiveness(policy.access_mode) < restrictiveness(current.access_mode)) {
if (!current) {
hosts[url] = policy
return
}
const capabilities = Object.fromEntries(HOST_CAPABILITIES.map(capability => {
const currentMode = current.capabilities[capability]
const incomingMode = policy.capabilities[capability]
return [capability, capabilityRestrictiveness(incomingMode) < capabilityRestrictiveness(currentMode)
? incomingMode
: currentMode]
})) as CapabilityPolicies
hosts[url] = {
access_mode: inferAccessMode(capabilities),
capabilities
}
}
export function inferAccessMode(capabilities: CapabilityPolicies): HostAccessMode {
for (const mode of ['ask', 'ask_every_time', 'structured', 'trusted', 'full_access'] as const) {
if (sameCapabilities(capabilities, PRESET_CAPABILITY_POLICIES[mode])) return mode
}
return 'custom'
}
/**
@@ -103,7 +189,12 @@ export function parseHostAccessPolicyFile(value: unknown): HostAccessPolicyFile
const urls = raw[field]
if (!Array.isArray(urls)) continue
for (const url of urls) {
if (typeof url === 'string') mergePolicy(hosts, url, { access_mode: mode })
if (typeof url === 'string') {
mergePolicy(hosts, url, {
access_mode: mode,
capabilities: presetCapabilityPolicies(mode)
})
}
}
}
@@ -150,8 +241,12 @@ export async function setHostAccessMode(
if (!isHostAccessMode(accessMode)) throw new Error(`unsupported host access mode: ${String(accessMode)}`)
const store = await readHostAccessPolicies(filePath)
const current = store.hosts[canonical]
const policy: HostAccessPolicy = {
access_mode: accessMode,
capabilities: accessMode === 'custom'
? current?.capabilities ?? { ...DEFAULT_CAPABILITY_POLICIES }
: presetCapabilityPolicies(accessMode),
updated_at: new Date().toISOString()
}
store.hosts[canonical] = policy
@@ -159,6 +254,66 @@ export async function setHostAccessMode(
return policy
}
/** Initialize a newly paired host without changing an existing or migrated
* policy. Missing policy records otherwise keep the legacy fail-closed
* Restricted behavior. */
export async function initializePairedHostAccessPolicy(
relayUrl: string,
filePath = hostAccessPolicyPath()
): Promise<HostAccessPolicy> {
const canonical = canonicalRelayUrl(relayUrl)
if (!canonical) throw new Error('host access policy requires a valid ws:// or wss:// relay URL')
const store = await readHostAccessPolicies(filePath)
const existing = store.hosts[canonical]
if (existing) return existing
const policy: HostAccessPolicy = {
access_mode: 'ask_every_time',
capabilities: presetCapabilityPolicies('ask_every_time'),
updated_at: new Date().toISOString()
}
store.hosts[canonical] = policy
await writeJsonAtomic(filePath, store)
return policy
}
export async function getHostCapabilityPolicies(
relayUrl: string,
filePath = hostAccessPolicyPath()
): Promise<CapabilityPolicies> {
const canonical = canonicalRelayUrl(relayUrl)
if (!canonical) return { ...DEFAULT_CAPABILITY_POLICIES }
return (await readHostAccessPolicies(filePath)).hosts[canonical]?.capabilities ??
{ ...DEFAULT_CAPABILITY_POLICIES }
}
export async function setHostCapabilityPolicy(
relayUrl: string,
capability: HostCapability,
mode: CapabilityAccessMode,
filePath = hostAccessPolicyPath()
): Promise<HostAccessPolicy> {
const canonical = canonicalRelayUrl(relayUrl)
if (!canonical) throw new Error('host capability policy requires a valid relay URL')
if (!HOST_CAPABILITIES.includes(capability)) throw new Error(`unsupported capability: ${capability}`)
if (!CAPABILITY_ACCESS_MODES.includes(mode)) throw new Error(`unsupported capability mode: ${mode}`)
const store = await readHostAccessPolicies(filePath)
const current = store.hosts[canonical] ?? {
access_mode: 'ask' as HostAccessMode,
capabilities: { ...DEFAULT_CAPABILITY_POLICIES }
}
if (current.capabilities[capability] === mode) return current
const policy: HostAccessPolicy = {
...current,
capabilities: { ...current.capabilities, [capability]: mode },
access_mode: 'custom',
updated_at: new Date().toISOString()
}
policy.access_mode = inferAccessMode(policy.capabilities)
store.hosts[canonical] = policy
await writeJsonAtomic(filePath, store)
return policy
}
export async function removeHostAccessPolicy(
relayUrl: string,
filePath = hostAccessPolicyPath()
@@ -191,3 +346,13 @@ export function effectiveHostAccessMode(
): HostAccessMode {
return storedMode === 'ask' && legacyToolsConsented ? 'trusted' : storedMode
}
export function effectiveHostCapabilityPolicies(
storedMode: HostAccessMode,
legacyToolsConsented: boolean,
storedCapabilities: CapabilityPolicies
): CapabilityPolicies {
return storedMode === 'ask' && legacyToolsConsented
? presetCapabilityPolicies('trusted')
: { ...storedCapabilities }
}
+162 -5
View File
@@ -20,6 +20,9 @@ import {
isApiEndpointShape,
isRelayEndpointShape,
} from './endpoint.js'
import { describeTransportSecurity } from './transportSecurity.js'
import https from 'node:https'
import { certificateDerToPem, comparePins, extractSpkiSha256 } from './certPin.js'
/**
* Per-candidate HEAD `/health` probe timeout. Matches Kotlin
@@ -157,6 +160,67 @@ function parseCandidate(v: unknown): EndpointCandidate | null {
const o = v as Record<string, unknown>
if (typeof o.role !== 'string') return null
const priority = typeof o.priority === 'number' ? o.priority : 0
if (typeof o.broker === 'object' && o.broker !== null && typeof o.proxy === 'object' && o.proxy !== null) {
if (!['outbound_broker', 'broker', 'relay_broker'].includes(o.role.toLowerCase())) return null
const broker = o.broker as Record<string, unknown>
const proxy = o.proxy as Record<string, unknown>
// The v1 pairing candidate does not require a redundant protocol_version;
// the fixed /v1/connect path supplies that version boundary. Accept an
// explicit 1 for compatibility, but reject any other advertised version.
const supportedVersion = broker.protocol_version === undefined || broker.protocol_version === 1
if (supportedVersion && typeof broker.url === 'string' && typeof broker.host_id === 'string' && /^[A-Za-z0-9_-]{22}$/.test(broker.host_id) && (broker.credential_kind === 'bootstrap' || broker.credential_kind === 'route') && typeof broker.token === 'string' && /^[A-Za-z0-9_-]{43}$/.test(broker.token) && typeof proxy.url === 'string' && typeof proxy.pin_sha256 === 'string' && typeof proxy.cert_der === 'string') {
try {
const base = new URL(proxy.url)
const brokerUrl = new URL(broker.url)
if (brokerUrl.protocol !== 'wss:' || brokerUrl.pathname !== '/v1/connect' || base.protocol !== 'https:') return null
return {
role: o.role, priority,
api: { host: base.hostname, port: Number(base.port || 443), tls: true },
relay: { url: `wss://${base.host}/relay/ws`, transportHint: 'wss' },
proxy: { url: proxy.url, pinSha256: proxy.pin_sha256, certificateDerBase64: proxy.cert_der, surfaces: ['relay'] },
broker: { url: broker.url, hostId: broker.host_id, credentialKind: broker.credential_kind, token: broker.token, ...((typeof broker.expires_at === 'string' || typeof broker.expires_at === 'number' || broker.expires_at === null) ? { expiresAt: broker.expires_at } : {}) },
...(typeof o.security === 'string' ? { security: o.security } : {}),
...(typeof o.recommended === 'boolean' ? { recommended: o.recommended } : {}),
...(typeof o.experimental === 'boolean' ? { experimental: o.experimental } : {}),
}
} catch { return null }
}
}
if (typeof o.proxy === 'object' && o.proxy !== null) {
const proxy = o.proxy as Record<string, unknown>
if (typeof proxy.url === 'string' && typeof proxy.pin_sha256 === 'string' && typeof proxy.cert_der === 'string') {
try {
const base = new URL(proxy.url)
if (base.protocol !== 'https:' || !base.hostname) return null
const port = Number(base.port || 443)
return {
role: o.role,
priority,
api: { host: base.hostname, port, tls: true },
relay: {
url: `wss://${base.host}/relay/ws`,
transportHint: 'wss',
},
proxy: {
url: proxy.url,
pinSha256: proxy.pin_sha256,
certificateDerBase64: proxy.cert_der,
...(typeof proxy.transport_hint === 'string'
? { transportHint: proxy.transport_hint }
: {}),
...(Array.isArray(proxy.surfaces)
? { surfaces: proxy.surfaces.filter((surface): surface is string => typeof surface === 'string') }
: {}),
},
...(typeof o.security === 'string' ? { security: o.security } : {}),
...(typeof o.recommended === 'boolean' ? { recommended: o.recommended } : {}),
...(typeof o.experimental === 'boolean' ? { experimental: o.experimental } : {}),
}
} catch {
return null
}
}
}
if (!isApiEndpointShape(o.api)) return null
if (!isRelayEndpointShape(o.relay)) return null
const api: ApiEndpoint = {
@@ -168,7 +232,11 @@ function parseCandidate(v: unknown): EndpointCandidate | null {
url: o.relay.url,
...(o.relay.transport_hint !== undefined ? { transportHint: o.relay.transport_hint } : {}),
}
return { role: o.role, priority, api, relay }
const candidate: EndpointCandidate = { role: o.role, priority, api, relay }
if (typeof o.security === 'string') candidate.security = o.security
if (typeof o.recommended === 'boolean') candidate.recommended = o.recommended
if (typeof o.experimental === 'boolean') candidate.experimental = o.experimental
return candidate
}
/**
@@ -350,6 +418,31 @@ export interface ProbeProgress {
export interface ProbeOptions {
onProbe?: (ev: ProbeProgress) => void
/** Existing Relay session required by the native proxy health route. */
sessionToken?: string
}
export function isValidPinnedProxyCandidate(candidate: EndpointCandidate): boolean {
return candidate.role.toLowerCase() === 'plugin_proxy' &&
candidate.security === 'pinned_tls' && candidate.recommended === true &&
candidate.proxy?.url.startsWith('https://') === true &&
/^sha256\/[A-Za-z0-9+/]{43}=$/.test(candidate.proxy.pinSha256) &&
typeof candidate.proxy.certificateDerBase64 === 'string' &&
candidate.proxy.certificateDerBase64.length <= 8_192 &&
/^[A-Za-z0-9+/]+={0,2}$/.test(candidate.proxy.certificateDerBase64)
}
function pinnedCertificate(candidate: EndpointCandidate): Buffer | null {
try {
const encoded = candidate.proxy?.certificateDerBase64
if (!encoded || encoded.length > 8_192 || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return null
const certificate = Buffer.from(encoded, 'base64')
return certificate.length > 0 && comparePins(candidate.proxy!.pinSha256, extractSpkiSha256(certificate))
? certificate
: null
} catch {
return null
}
}
/**
@@ -363,10 +456,52 @@ export interface ProbeOptions {
export async function probeCandidate(
c: EndpointCandidate,
signal: AbortSignal,
sessionToken?: string,
): Promise<ProbeResult> {
const started = Date.now()
const url = `${apiUrl(c.api)}/health`
if (c.broker) {
try {
const broker = new URL(c.broker.url)
const health = new URL('/health', `${broker.protocol === 'wss:' ? 'https:' : 'http:'}//${broker.host}`)
// Use the runtime fetch stack for the public broker health check. The
// packaged Bun runtime applies NODE_USE_SYSTEM_CA to fetch/WebSocket;
// node:https can use a different compatibility trust path and falsely
// reject the same Windows-trusted broker that the live WSS route opens.
// No Reach credential is sent, so this cannot consume the bootstrap.
const response = await fetch(health, { method: 'GET', signal, headers: { Accept: '*/*' } })
const reachable = response.ok
return { candidate: c, reachable, elapsedMs: Date.now() - started, ...(reachable ? {} : { error: 'Hermes Reach broker health check failed' }) }
} catch (error) {
return { candidate: c, reachable: false, elapsedMs: Date.now() - started, error: error instanceof Error ? error.message : String(error) }
}
}
// The secure proxy has one pinned origin with isolated service namespaces.
// Reachability remains anchored to its non-sensitive Relay health route.
const url = isValidPinnedProxyCandidate(c)
? `${c.proxy!.url.replace(/\/+$/, '')}/relay/health`
: `${apiUrl(c.api)}/health`
try {
if (isValidPinnedProxyCandidate(c)) {
const url = `${c.proxy!.url.replace(/\/+$/, '')}/relay/health`
const certificate = pinnedCertificate(c)
if (!certificate) {
return { candidate: c, reachable: false, elapsedMs: Date.now() - started,
error: 'paired certificate pin did not match' }
}
const reachable = await new Promise<boolean>((resolve, reject) => {
const request = https.get(url, {
rejectUnauthorized: true,
ca: certificateDerToPem(certificate),
signal,
headers: sessionToken ? { 'X-Hermes-Relay-Session': sessionToken } : undefined
}, response => {
response.resume()
resolve((response.statusCode ?? 500) >= 200 && (response.statusCode ?? 500) < 300)
})
request.once('error', reject)
})
return { candidate: c, reachable, elapsedMs: Date.now() - started }
}
const resp = await fetch(url, {
method: 'GET',
signal,
@@ -422,9 +557,13 @@ export async function probeCandidatesByPriority(
groups.set(c.priority, bucket)
}
const priorities = [...groups.keys()].sort((a, b) => a - b)
const orderedGroups = [
...priorities.map(priority => groups.get(priority) ?? []).filter(group => group.some(candidate => candidate.experimental !== true && candidate.role.toLowerCase() !== 'outbound_broker'))
.map(group => group.filter(candidate => candidate.experimental !== true && candidate.role.toLowerCase() !== 'outbound_broker')),
...priorities.map(priority => groups.get(priority) ?? []).map(group => group.filter(candidate => candidate.experimental === true || candidate.role.toLowerCase() === 'outbound_broker')).filter(group => group.length > 0),
]
for (const priority of priorities) {
const group = groups.get(priority) ?? []
for (const group of orderedGroups) {
// Fast path: any cached-reachable candidate wins without touching the
// network. Matches Kotlin's pre-race cache scan.
@@ -447,7 +586,7 @@ export async function probeCandidatesByPriority(
const timeout = AbortSignal.timeout(PROBE_TIMEOUT_MS)
// AbortSignal.any is available on Node ≥20 for combining signals.
const signal = AbortSignal.any([groupController.signal, timeout])
const result = await probeCandidate(c, signal)
const result = await probeCandidate(c, signal, opts.sessionToken)
probeCache.set(cacheKey(c), {
expiresAt: Date.now() + PROBE_CACHE_TTL_MS,
reachable: result.reachable,
@@ -489,6 +628,24 @@ export async function probeCandidatesByPriority(
)
}
/** Keep every fallback, but move encrypted routes ahead of plain ws:// by
* default. Original priority and array order remain the tie breakers within
* each security tier; callers can skip this helper for invite-order routing. */
export function secureFirstCandidates(candidates: EndpointCandidate[]): EndpointCandidate[] {
return candidates
.map((candidate, index) => ({ candidate, index }))
.sort((left, right) => {
const leftSecure = isValidPinnedProxyCandidate(left.candidate) || describeTransportSecurity(left.candidate.relay.url, left.candidate.role).encrypted
const rightSecure = isValidPinnedProxyCandidate(right.candidate) || describeTransportSecurity(right.candidate.relay.url, right.candidate.role).encrypted
const leftExperimental = left.candidate.experimental === true || left.candidate.role.toLowerCase() === 'outbound_broker'
const rightExperimental = right.candidate.experimental === true || right.candidate.role.toLowerCase() === 'outbound_broker'
return Number(leftExperimental) - Number(rightExperimental) ||
Number(rightSecure) - Number(leftSecure) ||
left.candidate.priority - right.candidate.priority || left.index - right.index
})
.map(({ candidate }, priority) => ({ ...candidate, priority }))
}
/**
* HMAC-SHA256 verification against the server's pairing secret.
*
+69 -10
View File
@@ -7,6 +7,21 @@ import { promises as fs } from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { initializePairedHostAccessPolicy } from './lib/hostAccessPolicy.js'
import type { EndpointCandidate } from './endpoint.js'
export interface StoredRouteCandidate {
role: string
priority: number
api: { host: string; port: number; tls: boolean }
relay: { url: string; transportHint?: string }
proxy?: { url: string; transportHint?: string; pinSha256: string; certificateDerBase64?: string; surfaces?: string[] }
security?: string
recommended?: boolean
experimental?: boolean
broker?: { url: string; hostId: string; credentialKind: 'bootstrap' | 'route'; token: string; expiresAt?: string | number | null }
}
export interface RemoteSessionRecord {
token: string
serverVersion: string | null
@@ -24,6 +39,11 @@ export interface RemoteSessionRecord {
* "custom", or null if unknown. Drives the contextual connect banner and
* the "Plain (on LAN)" style labels copied from the Android app. */
endpointRole?: string | null
/** Every route issued in the same v3 pairing invite. The token is shared by
* the relay instance, while certificate pins remain isolated per URL. */
routeCandidates?: StoredRouteCandidate[]
preferSecureRoutes?: boolean
routeCertPins?: Record<string, string>
/** Per-URL consent for exposing desktop tool handlers (file read/write,
* shell exec, search) to the remote agent. Granted explicitly on first
* chat/shell connect when tools would be wired. Missing → prompt; true
@@ -46,6 +66,9 @@ interface StoredRecord {
grants?: Record<string, number | null> | null
ttl_expires_at?: number | null
endpoint_role?: string | null
route_candidates?: StoredRouteCandidate[]
prefer_secure_routes?: boolean
route_cert_pins?: Record<string, string>
tools_consented?: boolean
computer_use_consented?: boolean
}
@@ -70,14 +93,21 @@ const storePath = () => pathOverride ?? defaultPath()
const emptyFile = (): StoredFile => ({ version: STORE_VERSION, sessions: {} })
const toRecord = (raw: StoredRecord): RemoteSessionRecord => ({
const toRecord = (raw: StoredRecord, routeUrl?: string): RemoteSessionRecord => ({
token: raw.token,
serverVersion: raw.server_version ?? null,
pairedAt: raw.paired_at,
certPinSha256: raw.cert_pin_sha256 ?? null,
certPinSha256: routeUrl
? raw.route_cert_pins?.[routeUrl] ?? raw.route_candidates?.find(candidate => candidate.relay.url === routeUrl)?.proxy?.pinSha256 ?? null
: raw.cert_pin_sha256 ?? null,
grants: raw.grants ?? null,
ttlExpiresAt: raw.ttl_expires_at ?? null,
endpointRole: raw.endpoint_role ?? null,
endpointRole: routeUrl
? raw.route_candidates?.find(candidate => candidate.relay.url === routeUrl)?.role ?? raw.endpoint_role ?? null
: raw.endpoint_role ?? null,
routeCandidates: raw.route_candidates,
preferSecureRoutes: raw.prefer_secure_routes ?? false,
routeCertPins: raw.route_cert_pins,
toolsConsented: raw.tools_consented ?? false,
computerUseConsented: raw.computer_use_consented ?? false
})
@@ -90,6 +120,9 @@ const fromRecord = (r: RemoteSessionRecord): StoredRecord => ({
grants: r.grants ?? null,
ttl_expires_at: r.ttlExpiresAt ?? null,
endpoint_role: r.endpointRole ?? null,
route_candidates: r.routeCandidates,
prefer_secure_routes: r.preferSecureRoutes ?? false,
route_cert_pins: r.routeCertPins,
tools_consented: r.toolsConsented ?? false,
computer_use_consented: r.computerUseConsented ?? false
})
@@ -129,13 +162,15 @@ const writeFile = async (file: StoredFile): Promise<void> => {
export const getSession = async (url: string): Promise<RemoteSessionRecord | null> => {
try {
const file = await readFile()
const raw = file.sessions[url]
const raw = file.sessions[url] ?? Object.values(file.sessions).find(record =>
record?.route_candidates?.some(candidate => candidate.relay.url === url)
)
if (!raw || typeof raw.token !== 'string' || !raw.token) {
return null
}
return toRecord(raw)
return toRecord(raw, file.sessions[url] ? undefined : url)
} catch {
return null
}
@@ -147,8 +182,13 @@ export interface SaveSessionOptions {
grants?: Record<string, number | null> | null
ttlExpiresAt?: number | null
endpointRole?: string | null
routeCandidates?: EndpointCandidate[]
preferSecureRoutes?: boolean
toolsConsented?: boolean
computerUseConsented?: boolean
/** Set only on a successful fresh pairing. Existing sessions and policy are
* never rewritten by routine token/session refreshes. */
initializeAccessPolicy?: boolean
}
export const saveSession = async (
@@ -166,15 +206,28 @@ export const saveSession = async (
try {
const file = await readFile()
const prev = file.sessions[url]
file.sessions[url] = fromRecord({
const ownerEntry = Object.entries(file.sessions).find(([ownerUrl, record]) =>
ownerUrl === url || record?.route_candidates?.some(candidate => candidate.relay.url === url)
)
const ownerUrl = ownerEntry?.[0] ?? url
const prev = ownerEntry?.[1]
const isAlternateRoute = ownerUrl !== url
const routePins = { ...(prev?.route_cert_pins ?? {}) }
if (isAlternateRoute && options.certPin !== undefined) {
if (options.certPin) routePins[url] = options.certPin
else delete routePins[url]
}
file.sessions[ownerUrl] = fromRecord({
token,
serverVersion,
pairedAt: options.pairedAt ?? Math.floor(Date.now() / 1000),
certPinSha256: options.certPin ?? prev?.cert_pin_sha256 ?? null,
certPinSha256: isAlternateRoute ? prev?.cert_pin_sha256 ?? null : options.certPin ?? prev?.cert_pin_sha256 ?? null,
grants: options.grants ?? prev?.grants ?? null,
ttlExpiresAt: options.ttlExpiresAt ?? prev?.ttl_expires_at ?? null,
endpointRole: options.endpointRole ?? prev?.endpoint_role ?? null,
routeCandidates: options.routeCandidates ?? prev?.route_candidates,
preferSecureRoutes: options.preferSecureRoutes ?? prev?.prefer_secure_routes ?? false,
routeCertPins: Object.keys(routePins).length ? routePins : prev?.route_cert_pins,
toolsConsented:
options.toolsConsented !== undefined
? options.toolsConsented
@@ -185,6 +238,9 @@ export const saveSession = async (
: (prev?.computer_use_consented ?? false)
})
await writeFile(file)
if (!prev && options.initializeAccessPolicy) {
await initializePairedHostAccessPolicy(url)
}
} catch {
// Persistence failures are non-fatal — next run just re-pairs.
}
@@ -194,11 +250,14 @@ export const deleteSession = async (url: string): Promise<void> => {
try {
const file = await readFile()
if (!(url in file.sessions)) {
const ownerUrl = url in file.sessions ? url : Object.entries(file.sessions).find(([, record]) =>
record?.route_candidates?.some(candidate => candidate.relay.url === url)
)?.[0]
if (!ownerUrl) {
return
}
delete file.sessions[url]
delete file.sessions[ownerUrl]
await writeFile(file)
} catch {
/* fail-closed */
+16
View File
@@ -0,0 +1,16 @@
import type { CapabilityPolicies, HostCapability } from '../lib/hostAccessPolicy.js'
import { DEFAULT_CAPABILITY_POLICIES } from '../lib/hostAccessPolicy.js'
let policies: CapabilityPolicies = { ...DEFAULT_CAPABILITY_POLICIES }
export function configureCapabilityPolicies(next: CapabilityPolicies): void {
policies = { ...next }
}
export function capabilityPolicy(capability: HostCapability) {
return policies[capability]
}
export function capabilitySummary(): CapabilityPolicies {
return { ...policies }
}
+23 -11
View File
@@ -1,4 +1,9 @@
import type { HostAccessMode } from '../lib/hostAccessPolicy.js'
import {
DEFAULT_CAPABILITY_POLICIES,
presetCapabilityPolicies,
type CapabilityPolicies,
type HostAccessMode
} from '../lib/hostAccessPolicy.js'
export type ComputerGrantMode = 'observe' | 'assist' | 'control'
@@ -22,6 +27,7 @@ export interface ComputerUseRuntime {
computerUseConsented: boolean
consentSource: 'stored' | 'prompted' | 'override' | 'none'
accessMode: HostAccessMode
capabilities: CapabilityPolicies
}
let activeGrant: ComputerGrant | null = null
@@ -30,7 +36,8 @@ let runtime: ComputerUseRuntime = {
url: null,
computerUseConsented: false,
consentSource: 'none',
accessMode: 'ask'
accessMode: 'ask',
capabilities: { ...DEFAULT_CAPABILITY_POLICIES }
}
function nowMs(): number {
@@ -101,13 +108,15 @@ export function getActiveComputerGrant(): ComputerGrant | null {
}
export function getComputerGrantSummary(): Record<string, unknown> {
if (runtime.accessMode === 'full_access') {
if (runtime.capabilities.screen_input === 'allow') {
return {
active: true,
mode: 'full_access',
mode: runtime.accessMode === 'full_access' ? 'full_access' : 'capability_allow',
expires_at: null,
scope: null,
reason: 'This host has Full Access.'
reason: runtime.accessMode === 'full_access'
? 'This host has Full Access.'
: 'Screen and input are allowed by this host policy.'
}
}
const grant = getActiveComputerGrant()
@@ -130,9 +139,11 @@ export function getComputerGrantSummary(): Record<string, unknown> {
}
export function configureComputerUseRuntime(next: Partial<ComputerUseRuntime>): void {
const capabilities = next.capabilities ?? (next.accessMode ? presetCapabilityPolicies(next.accessMode) : runtime.capabilities)
runtime = {
...runtime,
...next
...next,
capabilities
}
}
@@ -142,7 +153,8 @@ export function getComputerUseRuntimeSummary(): Record<string, unknown> {
consented: runtime.computerUseConsented,
consent_source: runtime.consentSource,
access_mode: runtime.accessMode,
full_access: runtime.accessMode === 'full_access'
full_access: runtime.accessMode === 'full_access',
capabilities: { ...runtime.capabilities }
}
}
@@ -154,10 +166,10 @@ export interface RequestComputerGrantInput {
}
export function requestComputerGrant(input: RequestComputerGrantInput): Record<string, unknown> {
if (runtime.accessMode === 'full_access') {
if (runtime.capabilities.screen_input === 'allow') {
return {
ok: true,
full_access: true,
full_access: runtime.accessMode === 'full_access',
grant: getComputerGrantSummary(),
message: 'This host already has Full Access; no task grant is required.'
}
@@ -212,13 +224,13 @@ export function cancelComputerGrant(reason = 'cancelled'): Record<string, unknow
}
export function hasComputerInputGrant(): boolean {
if (runtime.accessMode === 'full_access') return true
if (runtime.capabilities.screen_input === 'allow') return true
const grant = getActiveComputerGrant()
return grant?.mode === 'assist' || grant?.mode === 'control'
}
export function hasComputerObserveGrant(): boolean {
return runtime.accessMode === 'full_access' || getActiveComputerGrant() !== null
return runtime.capabilities.screen_input === 'allow' || getActiveComputerGrant() !== null
}
export function hasFullHostAccess(): boolean {
+167 -9
View File
@@ -20,6 +20,15 @@ import {
jobStatusHandler
} from './handlers/jobs.js'
import { powershellHandler } from './handlers/powershell.js'
import {
adbDevicesHandler,
adbInstallHandler,
adbLogcatHandler,
adbPullHandler,
adbPushHandler,
adbShellHandler
} from './handlers/adb.js'
import { usbDevicesHandler, usbRunHandler } from './handlers/usb.js'
import {
findPidByPortHandler,
killProcessHandler,
@@ -44,6 +53,13 @@ import {
} from './handlers/computer.js'
import type { ToolHandler } from './router.js'
import { readDesktopUseSettingsSync } from '../lib/desktopUseSettings.js'
import { approveComputerGrant } from './computerActionApproval.js'
import {
DEFAULT_CAPABILITY_POLICIES,
type CapabilityAccessMode,
type CapabilityPolicies,
type HostCapability
} from '../lib/hostAccessPolicy.js'
/** Experimental computer-use tools are registered in the local handler map
* but heartbeat-advertised only when persistently enabled or explicitly
@@ -91,9 +107,44 @@ const BASE_DESKTOP_HANDLERS: Record<string, ToolHandler> = {
desktop_clipboard_read: clipboardReadHandler,
desktop_clipboard_write: clipboardWriteHandler,
desktop_screenshot: screenshotHandler,
desktop_open_in_editor: openInEditorHandler
desktop_open_in_editor: openInEditorHandler,
desktop_usb_devices: usbDevicesHandler,
desktop_usb_run: usbRunHandler,
desktop_adb_devices: adbDevicesHandler,
desktop_adb_shell: adbShellHandler,
desktop_adb_push: adbPushHandler,
desktop_adb_pull: adbPullHandler,
desktop_adb_install: adbInstallHandler,
desktop_adb_logcat: adbLogcatHandler
}
export const RAW_EXECUTION_TOOLS = Object.freeze([
'desktop_terminal',
'desktop_powershell',
'desktop_spawn_detached',
'desktop_job_start'
])
export const FILE_TOOLS = Object.freeze([
'desktop_read_file', 'desktop_write_file', 'desktop_patch', 'desktop_search_files',
'desktop_copy_directory', 'desktop_zip', 'desktop_unzip', 'desktop_checksum', 'desktop_open_in_editor'
])
export const SCREEN_INPUT_TOOLS = Object.freeze([
'desktop_clipboard_read', 'desktop_clipboard_write', 'desktop_screenshot', ...DESKTOP_COMPUTER_USE_TOOLS
])
export const RAW_USB_TOOLS = Object.freeze([
'desktop_usb_devices',
'desktop_usb_run'
])
export const ADB_TOOLS = Object.freeze([
'desktop_adb_devices',
'desktop_adb_shell',
'desktop_adb_push',
'desktop_adb_pull',
'desktop_adb_install',
'desktop_adb_logcat'
])
export const USB_TOOLS = Object.freeze([...RAW_USB_TOOLS, ...ADB_TOOLS])
const COMPUTER_USE_HANDLERS: Record<string, ToolHandler> = {
desktop_computer_status: computerStatusHandler,
desktop_computer_screenshot: computerScreenshotHandler,
@@ -111,6 +162,10 @@ export const DESKTOP_HANDLERS: Record<string, ToolHandler> = {
export interface DesktopAdvertiseOptions {
computerUse?: boolean
structuredOnly?: boolean
usb?: boolean
adb?: boolean
capabilities?: CapabilityPolicies
}
function envEnabled(value: string | undefined): boolean {
@@ -139,10 +194,117 @@ export function shouldAdvertiseComputerUse(
export function desktopHandlers(
opts: DesktopAdvertiseOptions = {}
): Record<string, ToolHandler> {
if (opts.computerUse !== true) {
return BASE_DESKTOP_HANDLERS
const policies: CapabilityPolicies = opts.capabilities ?? {
...DEFAULT_CAPABILITY_POLICIES,
commands: opts.structuredOnly === true ? 'disabled' : 'allow',
files: 'allow',
screen_input: opts.computerUse === true ? 'ask' : 'disabled',
usb: opts.usb === true ? 'allow' : 'disabled'
}
const handlers = opts.computerUse === true && policies.screen_input !== 'disabled'
? DESKTOP_HANDLERS
: BASE_DESKTOP_HANDLERS
const raw = new Set(RAW_EXECUTION_TOOLS)
const files = new Set(FILE_TOOLS)
const screenInput = new Set(SCREEN_INPUT_TOOLS)
const rawUsb = new Set(RAW_USB_TOOLS)
const adb = new Set(ADB_TOOLS)
const capabilityFor = (name: string): HostCapability | null =>
raw.has(name) ? 'commands'
: files.has(name) ? 'files'
: screenInput.has(name) ? 'screen_input'
: rawUsb.has(name) || adb.has(name) ? 'usb'
: null
const guarded = Object.entries(handlers).flatMap(([name, handler]) => {
const capability = capabilityFor(name)
const mode = capability ? policies[capability] : 'allow'
if (mode === 'disabled') return []
if (adb.has(name) && opts.adb !== true) return []
if (mode !== 'ask' || name.startsWith('desktop_computer_') || name === 'desktop_patch') {
return [[name, handler] as const]
}
return [[name, guardCapabilityHandler(name, capability!, mode, handler)] as const]
})
return Object.fromEntries(guarded)
}
function guardCapabilityHandler(
tool: string,
capability: HostCapability,
mode: CapabilityAccessMode,
handler: ToolHandler
): ToolHandler {
if (mode !== 'ask') return handler
return async (args, ctx) => {
const approval = await approveComputerGrant({
mode: `${capability}.${tool.replace(/^desktop_/, '')}`,
durationSeconds: 120,
reason: typeof args.reason === 'string' && args.reason.trim()
? args.reason.trim()
: `Run ${tool.replaceAll('_', ' ')}`,
scope: buildCapabilityGrantScope(tool, capability, args),
interactive: ctx.interactive
})
if (!approval.approved) throw new Error(approval.reason || `${capability} request rejected locally`)
return handler(args, ctx)
}
}
const GRANT_PREVIEW_LIMIT = 2_000
function previewText(value: unknown): string | null {
if (typeof value !== 'string') return null
const clean = value.replaceAll(/[^\S\r\n]+/g, ' ').replaceAll(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '').trim()
if (!clean) return null
return clean.length > GRANT_PREVIEW_LIMIT ? `${clean.slice(0, GRANT_PREVIEW_LIMIT)}\n… preview truncated` : clean
}
/** Build the local approval context shown before an Ask-mode operation runs.
* Keep command text exact enough to review while summarizing large file bodies
* and environment maps rather than copying them into the bridge request. */
export function buildCapabilityGrantScope(
tool: string,
capability: HostCapability,
args: Record<string, unknown>
): Record<string, unknown> {
let action = tool.replace(/^desktop_/, '').replaceAll('_', ' ')
let preview: string | null = null
if (tool === 'desktop_powershell') {
action = 'PowerShell script'
preview = previewText(args.script)
} else if (['desktop_terminal', 'desktop_job_start', 'desktop_spawn_detached'].includes(tool)) {
action = tool === 'desktop_job_start' ? 'Background command' : 'Terminal command'
preview = previewText(args.command)
} else if (tool === 'desktop_read_file') {
action = 'Read file'
preview = previewText(args.path)
} else if (tool === 'desktop_write_file') {
action = 'Write file'
const path = previewText(args.path)
const contentLength = typeof args.content === 'string' ? args.content.length : null
preview = path ? `${path}${contentLength === null ? '' : ` (${contentLength.toLocaleString()} characters)`}` : null
} else if (tool === 'desktop_search_files') {
action = 'Search files'
const pattern = previewText(args.pattern)
const path = previewText(args.path)
preview = [pattern ? `Pattern: ${pattern}` : null, path ? `Path: ${path}` : null].filter(Boolean).join('\n') || null
} else if (capability === 'usb') {
action = tool.replace(/^desktop_/, '').replaceAll('_', ' ')
const executable = previewText(args.executable)
const command = previewText(args.command)
const argumentList = Array.isArray(args.arguments)
? args.arguments.filter(value => typeof value === 'string').join(' ')
: null
preview = previewText([executable, argumentList, command].filter(Boolean).join(' '))
}
return {
capability,
tool,
action,
...(preview ? { preview } : {})
}
return DESKTOP_HANDLERS
}
/** Stable list of advertised tool names — what the heartbeat claims to
@@ -151,11 +313,7 @@ export function desktopHandlers(
export function advertisedDesktopTools(
opts: DesktopAdvertiseOptions = {}
): readonly string[] {
if (opts.computerUse !== true) {
const experimental = new Set(DESKTOP_COMPUTER_USE_TOOLS)
return Object.freeze(Object.keys(DESKTOP_HANDLERS).filter(name => !experimental.has(name)))
}
return Object.freeze(Object.keys(DESKTOP_HANDLERS))
return Object.freeze(Object.keys(desktopHandlers(opts)))
}
export const DESKTOP_ADVERTISED_TOOLS: readonly string[] = advertisedDesktopTools({
+152
View File
@@ -0,0 +1,152 @@
import { spawn, spawnSync } from 'node:child_process'
import { resolve } from 'node:path'
import { approveComputerGrant } from '../computerActionApproval.js'
import { capabilityPolicy } from '../capabilityRuntime.js'
import type { ToolContext, ToolHandler } from '../router.js'
const MAX_OUTPUT_BYTES = 1024 * 1024
const DEFAULT_TIMEOUT_MS = 30_000
const MAX_TIMEOUT_MS = 120_000
const SERIAL_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/
export function adbBackendAvailable(env: NodeJS.ProcessEnv = process.env): boolean {
const executable = env.HERMES_RELAY_ADB_PATH?.trim() || 'adb'
const result = spawnSync(executable, ['version'], { windowsHide: true, stdio: 'ignore', env })
return !result.error && result.status === 0
}
function requiredString(value: unknown, name: string): string {
if (typeof value !== 'string' || !value.trim()) throw new Error(`missing or invalid "${name}" argument`)
return value.trim()
}
function serialArg(value: unknown): string {
const serial = requiredString(value, 'serial')
if (!SERIAL_PATTERN.test(serial)) throw new Error('invalid ADB serial')
return serial
}
function timeoutMs(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) && value > 0
? Math.min(Math.floor(value * 1000), MAX_TIMEOUT_MS)
: DEFAULT_TIMEOUT_MS
}
async function authorize(
operation: string,
scope: Record<string, unknown>,
reason: unknown,
ctx: ToolContext
): Promise<void> {
const policy = capabilityPolicy('usb')
if (policy === 'disabled') throw new Error('Raw USB access is disabled for this Hermes host')
if (policy === 'allow') return
const approval = await approveComputerGrant({
mode: `usb.${operation}`,
durationSeconds: 120,
reason: typeof reason === 'string' && reason.trim() ? reason.trim() : `Run brokered ADB ${operation}`,
scope,
interactive: ctx.interactive
})
if (!approval.approved) throw new Error(approval.reason || 'ADB request rejected locally')
}
async function runAdb(args: string[], ctx: ToolContext, timeout = DEFAULT_TIMEOUT_MS) {
const executable = process.env.HERMES_RELAY_ADB_PATH?.trim() || 'adb'
const child = spawn(executable, args, {
windowsHide: true,
stdio: ['ignore', 'pipe', 'pipe'],
env: process.env
})
let stdout = Buffer.alloc(0)
let stderr = Buffer.alloc(0)
let stdoutBytes = 0
let stderrBytes = 0
let killedBy: 'timeout' | 'abort' | null = null
child.stdout.on('data', (chunk: Buffer) => {
stdoutBytes += chunk.length
if (stdout.length < MAX_OUTPUT_BYTES) stdout = Buffer.concat([stdout, chunk.subarray(0, MAX_OUTPUT_BYTES - stdout.length)])
})
child.stderr.on('data', (chunk: Buffer) => {
stderrBytes += chunk.length
if (stderr.length < MAX_OUTPUT_BYTES) stderr = Buffer.concat([stderr, chunk.subarray(0, MAX_OUTPUT_BYTES - stderr.length)])
})
const timer = setTimeout(() => { killedBy = 'timeout'; child.kill('SIGKILL') }, timeout)
timer.unref?.()
const abort = () => { killedBy = 'abort'; child.kill('SIGKILL') }
ctx.abortSignal.addEventListener('abort', abort, { once: true })
try {
const exitCode = await new Promise<number>((resolve, reject) => {
child.once('error', reject)
child.once('close', code => {
if (killedBy) reject(new Error(killedBy === 'timeout' ? `ADB timed out after ${timeout}ms` : 'ADB request aborted'))
else resolve(code ?? 1)
})
})
return {
stdout: stdout.toString('utf8'),
stderr: stderr.toString('utf8'),
exit_code: exitCode,
output: {
limit_bytes_per_stream: MAX_OUTPUT_BYTES,
stdout: { bytes: stdoutBytes, captured_bytes: stdout.length, truncated: stdoutBytes > stdout.length },
stderr: { bytes: stderrBytes, captured_bytes: stderr.length, truncated: stderrBytes > stderr.length }
}
}
} finally {
clearTimeout(timer)
ctx.abortSignal.removeEventListener('abort', abort)
}
}
export const adbDevicesHandler: ToolHandler = async (args, ctx) => {
await authorize('devices', {}, args.reason, ctx)
const result = await runAdb(['devices', '-l'], ctx)
const devices = result.stdout.split(/\r?\n/).slice(1).filter(Boolean).map(line => {
const [serial = '', state = '', ...details] = line.trim().split(/\s+/)
const metadata = Object.fromEntries(details.filter(item => item.includes(':')).map(item => item.split(/:(.*)/s).slice(0, 2)))
return { serial, state, ...metadata }
})
return { ...result, devices }
}
export const adbShellHandler: ToolHandler = async (args, ctx) => {
const serial = serialArg(args.serial)
const command = requiredString(args.command, 'command')
await authorize('shell', { serial, command }, args.reason, ctx)
return runAdb(['-s', serial, 'shell', command], ctx, timeoutMs(args.timeout))
}
export const adbPushHandler: ToolHandler = async (args, ctx) => {
const serial = serialArg(args.serial)
const source = resolve(ctx.cwd, requiredString(args.source, 'source'))
const destination = requiredString(args.destination, 'destination')
await authorize('push', { serial, source, destination }, args.reason, ctx)
return runAdb(['-s', serial, 'push', source, destination], ctx, timeoutMs(args.timeout))
}
export const adbPullHandler: ToolHandler = async (args, ctx) => {
const serial = serialArg(args.serial)
const source = requiredString(args.source, 'source')
const destination = resolve(ctx.cwd, requiredString(args.destination, 'destination'))
await authorize('pull', { serial, source, destination }, args.reason, ctx)
return runAdb(['-s', serial, 'pull', source, destination], ctx, timeoutMs(args.timeout))
}
export const adbInstallHandler: ToolHandler = async (args, ctx) => {
const serial = serialArg(args.serial)
const apk = resolve(ctx.cwd, requiredString(args.apk, 'apk'))
const replace = args.replace !== false
await authorize('install', { serial, apk, replace }, args.reason, ctx)
return runAdb(['-s', serial, 'install', ...(replace ? ['-r'] : []), apk], ctx, timeoutMs(args.timeout))
}
export const adbLogcatHandler: ToolHandler = async (args, ctx) => {
const serial = serialArg(args.serial)
const lines = typeof args.lines === 'number' && Number.isFinite(args.lines)
? Math.max(1, Math.min(Math.floor(args.lines), 5000))
: 500
await authorize('logcat', { serial, lines }, args.reason, ctx)
return runAdb(['-s', serial, 'logcat', '-d', '-t', String(lines)], ctx, timeoutMs(args.timeout))
}
+4 -2
View File
@@ -12,6 +12,7 @@ import { promises as fs } from 'node:fs'
import * as path from 'node:path'
import { approveOrReject } from '../patchApproval.js'
import { capabilityPolicy } from '../capabilityRuntime.js'
import { hasFullHostAccess } from '../computerGrants.js'
import type { ToolContext, ToolHandler } from '../router.js'
@@ -248,7 +249,8 @@ export const patchHandler: ToolHandler = async (args, ctx) => {
// Interactive gate. The approver returns a decision — accepted or
// rejected with a reason — and never throws. If the user edited the
// diff we re-parse the edited version (strict; still no fuzz).
const decision = hasFullHostAccess()
const filesAllowed = hasFullHostAccess() || capabilityPolicy('files') === 'allow'
const decision = filesAllowed
? { accepted: true }
: await approveOrReject(patchText, {
targetFile: abs,
@@ -258,7 +260,7 @@ export const patchHandler: ToolHandler = async (args, ctx) => {
const reason = decision.reason ?? 'user rejected patch'
throw new Error(`patch rejected: ${reason}`)
}
let approvalTag: 'auto' | 'user' | 'edited' = hasFullHostAccess() ? 'auto' : 'user'
let approvalTag: 'auto' | 'user' | 'edited' = filesAllowed ? 'auto' : 'user'
if (decision.editedPatch && decision.editedPatch !== patchText) {
try {
hunks = parseUnifiedDiff(decision.editedPatch)
+98 -60
View File
@@ -10,10 +10,9 @@
// are unusable. Real-world fallout: the user reported scripts echoing back
// to the prompt instead of executing.
//
// We avoid all of that by spawning PowerShell directly (no cmd wrapper) and
// piping the script through stdin with `-Command -`. Script text never
// touches argv, so PowerShell's own parser doesn't have to compete with
// a host shell's quoting rules first.
// We avoid all of that by spawning PowerShell directly (no cmd wrapper) with
// a private temporary UTF-8 script file. Script text never touches argv, so
// PowerShell's parser doesn't compete with a host shell's quoting rules first.
//
// Discovery order (override with `prefer`):
// - 'pwsh' PowerShell 7+ (cross-platform). Preferred when present.
@@ -24,6 +23,9 @@
// PowerShell is required for this tool by definition.
import { spawn } from 'node:child_process'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { ToolHandler } from '../router.js'
@@ -38,6 +40,37 @@ const MAX_OUTPUT_BYTES = 4 * 1024 * 1024
type ShellPick = 'pwsh' | 'powershell'
interface CapturedStream {
text: string
bytes: number
captured_bytes: number
truncated: boolean
}
class BoundedCapture {
private readonly chunks: Buffer[] = []
private totalBytes = 0
private capturedBytes = 0
append(chunk: Buffer): void {
this.totalBytes += chunk.length
const remaining = MAX_OUTPUT_BYTES - this.capturedBytes
if (remaining <= 0) return
const captured = chunk.subarray(0, remaining)
this.chunks.push(captured)
this.capturedBytes += captured.length
}
result(): CapturedStream {
return {
text: Buffer.concat(this.chunks, this.capturedBytes).toString('utf8'),
bytes: this.totalBytes,
captured_bytes: this.capturedBytes,
truncated: this.totalBytes > this.capturedBytes
}
}
}
function argString(v: unknown, name: string): string {
if (typeof v !== 'string' || v.length === 0) {
throw new Error(`missing or invalid "${name}" argument`)
@@ -121,63 +154,56 @@ export const powershellHandler: ToolHandler = async (args, ctx) => {
const shell = await pickShell(prefer)
// Common args that suppress the user's $PROFILE (deterministic execution),
// refuse to read from a TTY (we're not interactive), and read the script
// from stdin (the `-` after -Command). We then close stdin so the script
// can't hang on Read-Host.
const shellArgs = ['-NoProfile', '-NonInteractive', '-Command', '-']
// A private temporary script avoids both cmd.exe quoting and PowerShell's
// line-oriented `-Command -` stdin parser. The latter can report exit 0 while
// failing to render some success-pipeline records consistently through a
// non-interactive host. Force UTF-8 and explicitly propagate the last native
// executable exit code when the script did not call `exit` itself.
const scriptDirectory = await mkdtemp(join(tmpdir(), 'hermes-relay-powershell-'))
const scriptPath = join(scriptDirectory, 'invoke.ps1')
const wrappedScript = [
'[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)',
'$OutputEncoding = [Console]::OutputEncoding',
script,
'if ($null -ne (Get-Variable LASTEXITCODE -ErrorAction SilentlyContinue)) { exit $LASTEXITCODE }'
].join('\n')
try {
await writeFile(scriptPath, wrappedScript, { encoding: 'utf8', mode: 0o600 })
} catch (error) {
await rm(scriptDirectory, { recursive: true, force: true })
throw error
}
const shellArgs = ['-NoProfile', '-NonInteractive']
if (process.platform === 'win32') {
shellArgs.push('-ExecutionPolicy', 'Bypass')
}
shellArgs.push('-File', scriptPath)
const start = Date.now()
const child = spawn(shell, shellArgs, {
cwd,
env: process.env,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true
})
let child
try {
child = spawn(shell, shellArgs, {
cwd,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true
})
} catch (error) {
await rm(scriptDirectory, { recursive: true, force: true })
throw error
}
let stdout = ''
let stderr = ''
let stdoutBytes = 0
let stderrBytes = 0
let truncated = false
const stdoutCapture = new BoundedCapture()
const stderrCapture = new BoundedCapture()
let killedBy: 'timeout' | 'abort' | null = null
child.stdout?.on('data', (chunk: Buffer) => {
stdoutBytes += chunk.length
if (stdoutBytes > MAX_OUTPUT_BYTES) {
truncated = true
try {
child.kill('SIGKILL')
} catch {
/* ignore */
}
return
}
stdout += chunk.toString('utf8')
stdoutCapture.append(chunk)
})
child.stderr?.on('data', (chunk: Buffer) => {
stderrBytes += chunk.length
if (stderrBytes > MAX_OUTPUT_BYTES) {
truncated = true
try {
child.kill('SIGKILL')
} catch {
/* ignore */
}
return
}
stderr += chunk.toString('utf8')
stderrCapture.append(chunk)
})
// Pipe script text through stdin verbatim — PowerShell parses it as if
// typed into an interactive session. Single quotes, here-strings, $vars,
// multiline blocks all work without re-quoting.
try {
child.stdin?.end(script + '\n')
} catch {
/* if write fails, the close handler will still resolve with whatever we got */
}
const timer = setTimeout(() => {
killedBy = 'timeout'
try {
@@ -204,12 +230,6 @@ export const powershellHandler: ToolHandler = async (args, ctx) => {
const exitCode = await new Promise<number>((resolve, reject) => {
child.on('error', e => reject(e))
child.on('close', (code, signal) => {
if (truncated) {
// Output cap fired SIGKILL — surface as a non-zero exit so the
// agent doesn't treat the truncated output as authoritative.
resolve(code ?? 137)
return
}
if (killedBy === 'timeout') {
reject(new Error(`timed out after ${timeoutMs}ms`))
return
@@ -226,16 +246,34 @@ export const powershellHandler: ToolHandler = async (args, ctx) => {
})
})
const stdout = stdoutCapture.result()
const stderr = stderrCapture.result()
const truncated = stdout.truncated || stderr.truncated
return {
stdout,
stderr,
stdout: stdout.text,
stderr: stderr.text,
exit_code: exitCode,
duration_ms: Date.now() - start,
shell,
truncated
truncated,
...(truncated ? { truncation_reason: 'output_limit' } : {}),
output: {
limit_bytes_per_stream: MAX_OUTPUT_BYTES,
stdout: {
bytes: stdout.bytes,
captured_bytes: stdout.captured_bytes,
truncated: stdout.truncated
},
stderr: {
bytes: stderr.bytes,
captured_bytes: stderr.captured_bytes,
truncated: stderr.truncated
}
}
}
} finally {
clearTimeout(timer)
ctx.abortSignal.removeEventListener('abort', onAbort)
await rm(scriptDirectory, { recursive: true, force: true })
}
}
+151
View File
@@ -0,0 +1,151 @@
import { spawn } from 'node:child_process'
import { platform } from 'node:os'
import { resolve } from 'node:path'
import { approveComputerGrant } from '../computerActionApproval.js'
import { capabilityPolicy } from '../capabilityRuntime.js'
import type { ToolContext, ToolHandler } from '../router.js'
const MAX_OUTPUT_BYTES = 1024 * 1024
const DEFAULT_TIMEOUT_MS = 30_000
const MAX_TIMEOUT_MS = 120_000
const MAX_ARGUMENTS = 128
const MAX_ARGUMENT_LENGTH = 8192
function requiredString(value: unknown, name: string): string {
if (typeof value !== 'string' || !value.trim() || value.includes('\0')) {
throw new Error(`missing or invalid "${name}" argument`)
}
return value.trim()
}
function argumentsList(value: unknown): string[] {
if (value === undefined) return []
if (!Array.isArray(value) || value.length > MAX_ARGUMENTS) {
throw new Error(`"arguments" must be an array with at most ${MAX_ARGUMENTS} entries`)
}
return value.map((argument, index) => {
if (typeof argument !== 'string' || argument.includes('\0') || argument.length > MAX_ARGUMENT_LENGTH) {
throw new Error(`invalid USB utility argument at index ${index}`)
}
return argument
})
}
function timeoutMs(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) && value > 0
? Math.min(Math.floor(value * 1000), MAX_TIMEOUT_MS)
: DEFAULT_TIMEOUT_MS
}
async function authorize(
operation: string,
scope: Record<string, unknown>,
reason: unknown,
ctx: ToolContext
): Promise<void> {
const policy = capabilityPolicy('usb')
if (policy === 'disabled') throw new Error('Raw USB access is disabled for this Hermes host')
if (policy === 'allow') return
const approval = await approveComputerGrant({
mode: `usb.${operation}`,
durationSeconds: 120,
reason: typeof reason === 'string' && reason.trim() ? reason.trim() : `Use raw USB ${operation}`,
scope,
interactive: ctx.interactive
})
if (!approval.approved) throw new Error(approval.reason || 'Raw USB request rejected locally')
}
async function runProcess(
executable: string,
args: string[],
ctx: ToolContext,
cwd?: string,
timeout = DEFAULT_TIMEOUT_MS
) {
const child = spawn(executable, args, {
cwd,
windowsHide: true,
shell: false,
stdio: ['ignore', 'pipe', 'pipe'],
env: process.env
})
let stdout = Buffer.alloc(0)
let stderr = Buffer.alloc(0)
let stdoutBytes = 0
let stderrBytes = 0
let killedBy: 'timeout' | 'abort' | null = null
child.stdout.on('data', (chunk: Buffer) => {
stdoutBytes += chunk.length
if (stdout.length < MAX_OUTPUT_BYTES) stdout = Buffer.concat([stdout, chunk.subarray(0, MAX_OUTPUT_BYTES - stdout.length)])
})
child.stderr.on('data', (chunk: Buffer) => {
stderrBytes += chunk.length
if (stderr.length < MAX_OUTPUT_BYTES) stderr = Buffer.concat([stderr, chunk.subarray(0, MAX_OUTPUT_BYTES - stderr.length)])
})
const timer = setTimeout(() => { killedBy = 'timeout'; child.kill('SIGKILL') }, timeout)
timer.unref?.()
const abort = () => { killedBy = 'abort'; child.kill('SIGKILL') }
ctx.abortSignal.addEventListener('abort', abort, { once: true })
try {
const exitCode = await new Promise<number>((resolveExit, reject) => {
child.once('error', reject)
child.once('close', code => {
if (killedBy) reject(new Error(killedBy === 'timeout' ? `USB utility timed out after ${timeout}ms` : 'USB request aborted'))
else resolveExit(code ?? 1)
})
})
return {
stdout: stdout.toString('utf8'),
stderr: stderr.toString('utf8'),
exit_code: exitCode,
executable,
arguments: args,
output: {
limit_bytes_per_stream: MAX_OUTPUT_BYTES,
stdout: { bytes: stdoutBytes, captured_bytes: stdout.length, truncated: stdoutBytes > stdout.length },
stderr: { bytes: stderrBytes, captured_bytes: stderr.length, truncated: stderrBytes > stderr.length }
}
}
} finally {
clearTimeout(timer)
ctx.abortSignal.removeEventListener('abort', abort)
}
}
function enumerationCommand(): { executable: string; arguments: string[]; format: string } {
if (platform() === 'win32') {
return {
executable: 'powershell.exe',
arguments: [
'-NoLogo', '-NoProfile', '-NonInteractive', '-Command',
"$ErrorActionPreference='Stop'; @(Get-CimInstance Win32_PnPEntity | Where-Object { $_.PNPDeviceID -like 'USB\\*' } | Select-Object Name,PNPDeviceID,Status,Service,Manufacturer) | ConvertTo-Json -Compress"
],
format: 'windows-pnp-json'
}
}
if (platform() === 'darwin') {
return { executable: 'system_profiler', arguments: ['SPUSBDataType', '-json'], format: 'system-profiler-json' }
}
return { executable: 'lsusb', arguments: [], format: 'lsusb-text' }
}
export const usbDevicesHandler: ToolHandler = async (args, ctx) => {
await authorize('devices', {}, args.reason, ctx)
const command = enumerationCommand()
const result = await runProcess(command.executable, command.arguments, ctx)
let devices: unknown = result.stdout.split(/\r?\n/).filter(Boolean)
if (command.format.endsWith('-json') && result.stdout.trim()) {
try { devices = JSON.parse(result.stdout) } catch { /* retain bounded raw lines */ }
}
return { ...result, format: command.format, devices }
}
export const usbRunHandler: ToolHandler = async (args, ctx) => {
const executable = requiredString(args.executable, 'executable')
const utilityArgs = argumentsList(args.arguments)
const cwd = typeof args.cwd === 'string' && args.cwd.trim() ? resolve(ctx.cwd, args.cwd.trim()) : ctx.cwd
await authorize('run', { executable, arguments: utilityArgs, cwd }, args.reason, ctx)
return runProcess(executable, utilityArgs, ctx, cwd, timeoutMs(args.timeout))
}
+9 -3
View File
@@ -27,12 +27,14 @@ import type { RelayTransport } from '../transport/RelayTransport.js'
import {
appendAudit,
auditDetails,
categorizeTool,
previewArgs,
resultExitCode,
summarizeResult
} from '../lib/auditLog.js'
import { VERSION } from '../version.js'
import { desktopDeviceId } from '../deviceIdentity.js'
import { getComputerGrantSummary, getComputerUseRuntimeSummary } from './computerGrants.js'
/** The payload shape server → client for a single tool invocation. */
@@ -234,7 +236,9 @@ export class DesktopToolRouter {
pid: process.pid,
started_at_ms: this.startedAtMs,
uptime_ms: Date.now() - this.startedAtMs,
interactive: this.interactive
interactive: this.interactive,
device_id: desktopDeviceId(),
device_name: os.hostname()
}
if (this.advertisedTools.some(name => name.startsWith('desktop_computer_'))) {
const runtime = getComputerUseRuntimeSummary()
@@ -286,7 +290,7 @@ export class DesktopToolRouter {
}
const controller = new AbortController()
const timeoutMs = tool.startsWith('desktop_computer_')
const timeoutMs = tool.startsWith('desktop_computer_') || tool.startsWith('desktop_adb_') || tool.startsWith('desktop_usb_')
? COMPUTER_USE_HANDLER_TIMEOUT_MS
: HANDLER_TIMEOUT_MS
const timeoutTimer = setTimeout(() => {
@@ -321,7 +325,8 @@ export class DesktopToolRouter {
duration_ms: Date.now() - startedAt,
exit_code: resultExitCode(result),
args_preview: previewArgs(args),
summary: summarizeResult(result)
summary: summarizeResult(result),
...auditDetails(args, result)
})
} catch (e) {
clearTimeout(timeoutTimer)
@@ -350,6 +355,7 @@ export class DesktopToolRouter {
host_url: this.hostUrl,
duration_ms: Date.now() - startedAt,
args_preview: previewArgs(args),
...auditDetails(args),
error: message
})
}
+156
View File
@@ -0,0 +1,156 @@
import { createHash, randomBytes } from 'node:crypto'
import { Duplex } from 'node:stream'
import * as tls from 'node:tls'
import { certificateDerToPem, comparePins, extractSpkiSha256, peerCertificateDer } from '../certPin.js'
export interface BrokerRouteConfig {
url: string
hostId: string
credentialKind: 'bootstrap' | 'route'
token: string
innerUrl: string
innerPinSha256: string
innerCertificateDerBase64: string
}
type EventName = 'open' | 'message' | 'close' | 'error'
type Listener = (...args: any[]) => void
class BrokerByteStream extends Duplex {
private matchedResolve!: () => void
private matchedReject!: (error: Error) => void
readonly matched = new Promise<void>((resolve, reject) => { this.matchedResolve = resolve; this.matchedReject = reject })
private binary = false
private matchTimer: ReturnType<typeof setTimeout>
constructor(private readonly ws: WebSocket, registration: Record<string, unknown>) {
super()
this.matchTimer = setTimeout(() => this.matchedReject(new Error('Hermes Reach host match timed out')), 10_000)
ws.binaryType = 'arraybuffer'
ws.addEventListener('open', () => ws.send(JSON.stringify(registration)))
ws.addEventListener('message', event => {
if (!this.binary) {
try {
const message = JSON.parse(String(event.data)) as { type?: string; code?: string; protocol_version?: number; stream_id?: string }
if (message.type === 'matched' && message.protocol_version === 1 && typeof message.stream_id === 'string' && /^[A-Za-z0-9_-]{22}$/.test(message.stream_id)) { clearTimeout(this.matchTimer); this.binary = true; this.matchedResolve(); return }
if (message.type === 'error') this.matchedReject(new Error(`Hermes Reach rejected route: ${message.code ?? 'unknown'}`))
} catch { this.matchedReject(new Error('Hermes Reach returned an invalid match response')) }
return
}
const data = event.data
if (data instanceof ArrayBuffer) this.push(Buffer.from(data))
else if (ArrayBuffer.isView(data)) this.push(Buffer.from(data.buffer, data.byteOffset, data.byteLength))
else this.destroy(new Error('Hermes Reach switched away from binary tunnel records'))
})
ws.addEventListener('close', () => { this.push(null); if (!this.binary) this.matchedReject(new Error('Hermes Reach closed before matching the host')) })
ws.addEventListener('error', () => { const error = new Error('Hermes Reach WebSocket failed'); this.matchedReject(error); this.destroy(error) })
}
_read(): void {}
_write(chunk: Buffer, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
if (this.ws.readyState !== WebSocket.OPEN) { callback(new Error('Hermes Reach tunnel is not open')); return }
if (chunk.byteLength > 1024 * 1024) { callback(new Error('Hermes Reach record exceeds 1 MiB')); return }
this.ws.send(chunk); callback()
}
_destroy(error: Error | null, callback: (error?: Error | null) => void): void { clearTimeout(this.matchTimer); try { this.ws.close() } finally { callback(error) } }
}
export class BrokerRelaySocket {
readyState = 0
private openEmitted = false
private listeners = new Map<EventName, Listener[]>()
private buffer = Buffer.alloc(0)
private fragments: Buffer[] = []
private fragmentOpcode = 0
constructor(private readonly socket: tls.TLSSocket) {
socket.on('data', chunk => { this.buffer = Buffer.concat([this.buffer, chunk]); this.parseFrames() })
socket.on('error', error => this.emit('error', { message: error.message }))
socket.on('close', () => { this.readyState = 3; this.emit('close', { code: 1006, reason: 'Hermes Reach tunnel closed' }) })
}
addEventListener(type: EventName, listener: Listener): void {
const list = this.listeners.get(type) ?? []
list.push(listener)
this.listeners.set(type, list)
// openBrokerRelaySocket completes the TLS and HTTP upgrade before it
// returns. Await continuations can therefore subscribe after the queued
// open event ran. Replay that one-shot state to late listeners, while
// listeners registered before the queued emission still receive it once.
if (type === 'open' && this.readyState === 1 && this.openEmitted) {
queueMicrotask(() => listener())
}
}
opened(): void { this.readyState = 1; queueMicrotask(() => this.emit('open')) }
send(data: string): void { this.socket.write(frame(Buffer.from(data), 1)) }
close(code = 1000, reason = ''): void { if (this.readyState < 2) { this.readyState = 2; const body = Buffer.alloc(2 + Buffer.byteLength(reason)); body.writeUInt16BE(code); body.write(reason, 2); this.socket.end(frame(body, 8)) } }
private emit(type: EventName, event?: unknown): void {
if (type === 'open') this.openEmitted = true
for (const listener of this.listeners.get(type) ?? []) listener(event)
}
private parseFrames(): void {
while (this.buffer.length >= 2) {
const first = this.buffer[0]!, second = this.buffer[1]!
if ((first & 0x70) !== 0 || (second & 0x80) !== 0) { this.socket.destroy(new Error('invalid inner WebSocket frame')); return }
let length = second & 0x7f, offset = 2
if (length === 126) { if (this.buffer.length < 4) return; length = this.buffer.readUInt16BE(2); offset = 4 }
else if (length === 127) { if (this.buffer.length < 10) return; const wide = this.buffer.readBigUInt64BE(2); if (wide > 1024n * 1024n) { this.socket.destroy(new Error('inner Relay frame exceeds 1 MiB')); return } length = Number(wide); offset = 10 }
const masked = (second & 0x80) !== 0, maskBytes = masked ? 4 : 0
if (this.buffer.length < offset + maskBytes + length) return
const mask = masked ? this.buffer.subarray(offset, offset + 4) : null
offset += maskBytes
const payload = Buffer.from(this.buffer.subarray(offset, offset + length)); this.buffer = this.buffer.subarray(offset + length)
if (mask) for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4]!
const opcode = first & 0x0f, fin = (first & 0x80) !== 0
if (opcode >= 8 && (!fin || length > 125)) { this.socket.destroy(new Error('invalid inner WebSocket control frame')); return }
if (opcode === 0 && this.fragments.length === 0) { this.socket.destroy(new Error('unexpected inner WebSocket continuation')); return }
if (opcode !== 0 && opcode < 8 && this.fragments.length !== 0) { this.socket.destroy(new Error('interleaved inner WebSocket message')); return }
if (opcode === 8) { this.close(); return }
if (opcode === 9) { this.socket.write(frame(payload, 10)); continue }
if (opcode === 10) continue
if (opcode !== 0) this.fragmentOpcode = opcode
this.fragments.push(payload)
if (this.fragments.reduce((total, part) => total + part.length, 0) > 1024 * 1024) { this.socket.destroy(new Error('inner Relay message exceeds 1 MiB')); return }
if (fin) { const message = Buffer.concat(this.fragments); const type = this.fragmentOpcode; this.fragments = []; this.fragmentOpcode = 0; this.emit('message', { data: type === 1 ? message.toString('utf8') : message }) }
}
}
}
function frame(payload: Buffer, opcode: number): Buffer {
const mask = randomBytes(4)
const head = payload.length < 126 ? Buffer.from([0x80 | opcode, 0x80 | payload.length]) : Buffer.from([0x80 | opcode, 0xfe, payload.length >> 8, payload.length & 0xff])
const body = Buffer.from(payload); for (let i = 0; i < body.length; i++) body[i] ^= mask[i % 4]!
return Buffer.concat([head, mask, body])
}
export async function openBrokerRelaySocket(config: BrokerRouteConfig): Promise<BrokerRelaySocket> {
const connectionId = randomBytes(16).toString('base64url')
const outer = new WebSocket(new URL('/v1/connect', config.url).toString())
const stream = new BrokerByteStream(outer, { type: 'register', protocol_version: 1, role: 'client', host_id: config.hostId, connection_id: connectionId, credential_kind: config.credentialKind, token: config.token })
await stream.matched
const inner = new URL(config.innerUrl)
const certificate = Buffer.from(config.innerCertificateDerBase64, 'base64')
if (!comparePins(config.innerPinSha256, extractSpkiSha256(certificate))) {
stream.destroy(new Error('Hermes Reach inner Secure Link certificate pin mismatch'))
throw new Error('Hermes Reach inner Secure Link certificate pin mismatch')
}
const secure = tls.connect({
socket: stream,
servername: inner.hostname,
rejectUnauthorized: true,
ca: certificateDerToPem(certificate),
})
await new Promise<void>((resolve, reject) => { secure.once('secureConnect', resolve); secure.once('error', reject) })
const raw = peerCertificateDer(secure)
if (!raw || !comparePins(config.innerPinSha256, extractSpkiSha256(raw))) { secure.destroy(); throw new Error('Hermes Reach inner Secure Link certificate pin mismatch') }
const identityError = tls.checkServerIdentity(inner.hostname, secure.getPeerCertificate(true))
if (identityError) { secure.destroy(); throw identityError }
const key = randomBytes(16).toString('base64')
secure.write(`GET ${inner.pathname || '/relay/ws'}${inner.search} HTTP/1.1\r\nHost: ${inner.host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`)
let response = Buffer.alloc(0)
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => { secure.destroy(); reject(new Error('Hermes Reach inner WebSocket upgrade timed out')) }, 10_000)
const onData = (chunk: Buffer) => { response = Buffer.concat([response, chunk]); if (response.length > 32 * 1024) { clearTimeout(timer); secure.destroy(); reject(new Error('Hermes Reach inner WebSocket upgrade headers too large')); return } const end = response.indexOf('\r\n\r\n'); if (end < 0) return; clearTimeout(timer); secure.off('data', onData); const header = response.subarray(0, end).toString('utf8'); const accept = createHash('sha1').update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64'); if (!/^HTTP\/1\.1 101 /i.test(header) || !header.toLowerCase().includes(`sec-websocket-accept: ${accept.toLowerCase()}`)) reject(new Error('Hermes Reach inner WebSocket upgrade failed')); else { const rest = response.subarray(end + 4); if (rest.length) secure.unshift(rest); resolve() } }
secure.on('data', onData); secure.once('error', reject)
})
const socket = new BrokerRelaySocket(secure); socket.opened(); return socket
}
+73 -17
View File
@@ -12,13 +12,14 @@ import { randomUUID } from 'node:crypto'
import { EventEmitter } from 'node:events'
import * as tls from 'node:tls'
import { comparePins, extractSpkiSha256, isSecureUrl, pinKey } from '../certPin.js'
import { certificateDerToPem, comparePins, extractSpkiSha256, isSecureUrl, peerCertificateDer, pinKey } from '../certPin.js'
import type { GatewayEvent } from '../gatewayTypes.js'
import { CircularBuffer } from '../lib/circularBuffer.js'
import { getSession, saveSession } from '../remoteSessions.js'
import { installWindowsSystemCaTrust } from '../windowsSystemCa.js'
import type { Transport } from './Transport.js'
import { openBrokerRelaySocket, type BrokerRouteConfig } from './BrokerRelaySocket.js'
const MAX_LOG_LINES = 200
const MAX_LOG_LINE_BYTES = 4096
@@ -80,7 +81,7 @@ interface WSLike {
addEventListener(type: 'error', listener: (ev: WSErrorEvent) => void): void
}
type WSFactory = (url: string) => WSLike
type WSFactory = (url: string, headers?: Record<string, string>, pinnedCertificatePem?: string) => WSLike
export interface AuthMeta {
/** Per-channel grant expiry (epoch seconds; `null` = never). Shape matches
@@ -91,6 +92,7 @@ export interface AuthMeta {
/** Server's hint about the transport it's running on — `"wss"` / `"ws"` / `"unknown"`.
* Used by the contextual connect banner so we can tell the user what they're on. */
transportHint: string | null
routeCredential: { kind: 'broker_route'; brokerUrl: string; hostId: string; credentialId: string; token: string; expiresAt: number | null } | null
}
export type AuthOutcome =
@@ -102,7 +104,7 @@ export type AuthOutcome =
* auth.ok seen; `reconnecting` = socket dropped, backoff timer armed. */
type ReconnectState = 'idle' | 'connecting' | 'connected' | 'reconnecting'
const defaultWSFactory: WSFactory = url => {
const defaultWSFactory: WSFactory = (url, headers, pinnedCertificatePem) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const Ctor = (globalThis as any).WebSocket
@@ -110,6 +112,19 @@ const defaultWSFactory: WSFactory = url => {
throw new Error('RelayTransport: global WebSocket not available. Need Node >=21.')
}
if ((headers && Object.keys(headers).length) || pinnedCertificatePem) {
// Bun's compiled runtime supports upgrade headers and scoped TLS options.
// Trusting the exact certificate observed during pin verification binds
// the live handshake to that check and preserves hostname validation.
const options = {
...(headers ? { headers } : {}),
...(pinnedCertificatePem ? { tls: { rejectUnauthorized: true, ca: pinnedCertificatePem } } : {})
}
// Bun accepts options as the second argument. Passing an empty protocols
// array plus a third options argument silently drops TLS settings and
// fails private-certificate handshakes.
return new Ctor(url, options) as WSLike
}
return new Ctor(url) as WSLike
}
@@ -119,6 +134,11 @@ export interface RelayTransportConfig {
pairingCode?: string
/** Previously-minted session token for reconnection. */
sessionToken?: string
/** Pin supplied by the operator-reviewed pairing invite before a session
* record exists. It is compared before the first WebSocket is opened. */
expectedCertPin?: string
/** Authenticate a native Relay-only secure proxy WebSocket upgrade. */
sessionHeader?: boolean
/** Human-readable label for the "Paired Devices" list. */
deviceName?: string
/** Machine hostname used as a fallback identity by newer relays. */
@@ -150,6 +170,7 @@ export interface RelayTransportConfig {
* Returning false aborts reconnect — used for credential-purge races
* (e.g. user ran `hermes-relay pair --reset` mid-session). */
reconnectGate?: () => boolean
broker?: BrokerRouteConfig
/** When set false, suppress the `desktop.workspace` advertisement
* fired on first auth.ok. Default: true — every connection sends a
* one-shot workspace envelope (cwd / git state / hostname). One-shot
@@ -183,6 +204,7 @@ export interface RelayTransportConfig {
export class RelayTransport extends EventEmitter implements Transport {
private ws: WSLike | null = null
private wsFactory: WSFactory
private pinnedCertificatePem: string | undefined
private cfg: RelayTransportConfig
private reqId = 0
private logs = new CircularBuffer<string>(MAX_LOG_LINES)
@@ -197,7 +219,7 @@ export class RelayTransport extends EventEmitter implements Transport {
/** Auth.ok metadata captured on handshake — surfaces grants / ttl / transport
* hint to the CLI so `hermes-relay status`, the connect banner, and future
* TTL-aware flows don't have to re-RPC for data the handshake already carried. */
authMeta: AuthMeta = { grants: null, ttlExpiresAt: null, transportHint: null }
authMeta: AuthMeta = { grants: null, ttlExpiresAt: null, transportHint: null, routeCredential: null }
private authSuccessObservers: Array<(token: string, serverVersion: string | null, meta: AuthMeta) => void> = []
private authSettlers: Array<(r: AuthOutcome) => void> = []
private authFailReason: null | string = null
@@ -324,9 +346,24 @@ export class RelayTransport extends EventEmitter implements Transport {
this.teardownSocket(-1, msg)
}, AUTH_TIMEOUT_MS)
// Hermes Reach carries the inner Secure Link TLS/WS connection through an
// opaque byte rendezvous. Its factory validates the inner QR SPKI and
// hostname before exposing the WebSocket.
if (this.cfg.broker) {
try {
const ws = await openBrokerRelaySocket(this.cfg.broker)
this.bindSocket(ws)
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
this.authFailReason = msg; this.teardownSocket(-1, msg)
}
return
}
// TOFU: probe the TLS peer cert BEFORE the WebSocket handshake so we can
// refuse to open the WS on a pin mismatch. No-op for ws://.
if (isSecureUrl(this.cfg.url)) {
this.pinnedCertificatePem = undefined
try {
await this.verifyOrCapturePin()
} catch (e) {
@@ -343,7 +380,12 @@ export class RelayTransport extends EventEmitter implements Transport {
let ws: WSLike
try {
ws = this.wsFactory(this.cfg.url)
const token = this.sessionToken ?? this.cfg.sessionToken
ws = this.wsFactory(
this.cfg.url,
this.cfg.sessionHeader && token ? { 'X-Hermes-Relay-Session': token } : undefined,
this.pinnedCertificatePem
)
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
this.pushLog(`[ws] factory failed: ${msg}`)
@@ -353,8 +395,11 @@ export class RelayTransport extends EventEmitter implements Transport {
return
}
this.ws = ws
this.bindSocket(ws)
}
private bindSocket(ws: WSLike): void {
this.ws = ws
ws.addEventListener('open', () => {
this.pushLog(`[ws] open → ${this.cfg.url}`)
this.sendAuth()
@@ -392,18 +437,18 @@ export class RelayTransport extends EventEmitter implements Transport {
const port = parseInt(u.port || '443', 10)
const key = pinKey(this.cfg.url)
const stored = await getSession(this.cfg.url)
const expectedPin = stored?.certPinSha256 ?? null
const expectedPin = stored?.certPinSha256 ?? this.cfg.expectedCertPin ?? null
const actualPin = await new Promise<string>((resolve, reject) => {
const verified = await new Promise<{ pin: string; der: Buffer }>((resolve, reject) => {
const socket = tls.connect({
host,
port,
servername: host,
// Let Node's default CA store run. Self-signed servers still TOFU-
// pin on subsequent connects, but the first probe requires a valid
// chain. If users need a self-signed flow, they can pre-seed a pin
// via the Android app or a future `--trust-self-signed` flag.
rejectUnauthorized: true
// A server-advertised pin is authoritative trust material. Permit the
// handshake to reach pin comparison even when the private proxy uses
// a locally issued certificate; without a pin, normal CA validation
// remains mandatory before TOFU capture.
rejectUnauthorized: !expectedPin
})
const timer = setTimeout(() => {
@@ -417,8 +462,7 @@ export class RelayTransport extends EventEmitter implements Transport {
// `detailed=false` here; we only need `raw` (DER). We always pin
// the leaf — intermediates rotate on CA renewal and would cause
// spurious mismatches.
const peer = socket.getPeerCertificate(false)
const raw = (peer as unknown as { raw?: Buffer })?.raw
const raw = peerCertificateDer(socket)
if (!raw || !Buffer.isBuffer(raw) || raw.length === 0) {
socket.destroy()
@@ -428,7 +472,7 @@ export class RelayTransport extends EventEmitter implements Transport {
}
const pin = extractSpkiSha256(raw)
socket.end()
resolve(pin)
resolve({ pin, der: raw })
} catch (e) {
socket.destroy()
reject(e instanceof Error ? e : new Error(String(e)))
@@ -441,6 +485,7 @@ export class RelayTransport extends EventEmitter implements Transport {
})
})
const actualPin = verified.pin
if (expectedPin) {
if (!comparePins(expectedPin, actualPin)) {
// Surface a user-friendly remediation path. The session file carries
@@ -453,6 +498,7 @@ export class RelayTransport extends EventEmitter implements Transport {
)
}
this.pushLog(`[tofu] pin match for ${key}`)
this.pinnedCertificatePem = certificateDerToPem(verified.der)
return
}
@@ -652,7 +698,17 @@ export class RelayTransport extends EventEmitter implements Transport {
: null
const rawHint = payload.transport_hint
const transportHint = typeof rawHint === 'string' ? rawHint : null
this.authMeta = { grants, ttlExpiresAt, transportHint }
let routeCredential: AuthMeta['routeCredential'] = null
const rawRoute = payload.route_credential
if (this.cfg.broker && rawRoute && typeof rawRoute === 'object' && !Array.isArray(rawRoute)) {
const route = rawRoute as Record<string, unknown>
const sameAuthority = (() => { try { return new URL(String(route.broker_url)).origin === new URL(this.cfg.broker!.url).origin } catch { return false } })()
const expiresAt = route.expires_at === null ? null : typeof route.expires_at === 'number' && Number.isFinite(route.expires_at) && route.expires_at > Date.now() / 1000 ? route.expires_at : undefined
if (route.kind === 'broker_route' && sameAuthority && route.host_id === this.cfg.broker.hostId && typeof route.credential_id === 'string' && /^[A-Za-z0-9_-]{1,256}$/.test(route.credential_id) && typeof route.token === 'string' && /^[A-Za-z0-9_-]{32,512}$/.test(route.token) && expiresAt !== undefined) {
routeCredential = { kind: 'broker_route', brokerUrl: String(route.broker_url), hostId: String(route.host_id), credentialId: route.credential_id, token: route.token, expiresAt }
}
}
this.authMeta = { grants, ttlExpiresAt, transportHint, routeCredential }
this.pushLog(
`[auth] ok (server ${this.serverVersion ?? '?'}, transport=${transportHint ?? '?'}, ttl=${
+55
View File
@@ -0,0 +1,55 @@
export type TransportSecurityKind = 'secure-link' | 'broker' | 'tls' | 'overlay' | 'plain'
export interface TransportSecurity {
kind: TransportSecurityKind
encrypted: boolean
label: string
detail: string
}
function isTailscaleIpv4(hostname: string): boolean {
const parts = hostname.split('.').map(Number)
return parts.length === 4 && parts.every(part => Number.isInteger(part) && part >= 0 && part <= 255) &&
parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127
}
export function isOverlayRoute(url: string, endpointRole?: string | null): boolean {
const role = endpointRole?.trim().toLowerCase() ?? ''
if (role === 'tailscale' || role === 'wireguard' || role.startsWith('wireguard-')) return true
try {
const hostname = new URL(url).hostname.toLowerCase()
return hostname.endsWith('.ts.net') || isTailscaleIpv4(hostname)
} catch {
return false
}
}
/** Describe the protection actually carrying relay traffic. WSS is TLS;
* ws:// over a known Tailscale/WireGuard route is still encrypted by the
* authenticated overlay. All other ws:// routes are plain transport. */
export function describeTransportSecurity(url: string, endpointRole?: string | null): TransportSecurity {
const role = endpointRole?.trim().toLowerCase()
if (role === 'plugin_proxy') {
return { kind: 'secure-link', encrypted: true, label: 'Hermes Secure Link', detail: 'Pinned TLS protects this Relay connection and verifies the paired endpoint.' }
}
if (role === 'outbound_broker' || role === 'relay_broker' || role === 'broker') {
const encrypted = url.trim().toLowerCase().startsWith('wss://')
return {
kind: 'broker', encrypted,
label: encrypted ? 'Broker hop protected with TLS' : 'Broker hop is not protected',
detail: encrypted
? 'Hermes Reach provides outbound reachability. TLS protects the broker hop only; payload end-to-end protection is reported separately when the protocol validates it.'
: 'Hermes Reach provides outbound reachability, but this broker hop is not using WSS. No payload end-to-end protection is implied.'
}
}
try {
if (new URL(url).protocol === 'wss:') {
return { kind: 'tls', encrypted: true, label: 'Encrypted with TLS', detail: 'Relay traffic is protected end to end with WSS.' }
}
} catch { /* Invalid URLs are treated as unprotected below. */ }
if (isOverlayRoute(url, endpointRole)) {
const name = endpointRole?.toLowerCase().includes('wireguard') ? 'WireGuard' : 'Tailscale'
return { kind: 'overlay', encrypted: true, label: `Encrypted by ${name}`, detail: `Relay traffic travels inside the ${name} encrypted overlay.` }
}
return { kind: 'plain', encrypted: false, label: 'Unencrypted relay connection', detail: 'Use WSS or an authenticated Tailscale/WireGuard route for encryption.' }
}
+1 -1
View File
@@ -1,2 +1,2 @@
// Regenerated from package.json by gen:version script. Do not edit by hand.
export const VERSION = "0.4.0-alpha.7" as const
export const VERSION = "0.4.0-alpha.8" as const
+14 -1
View File
@@ -1,17 +1,30 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { categorizeTool, resultExitCode, summarizeResult } from '../src/lib/auditLog.js'
import { auditDetails, categorizeTool, resultExitCode, summarizeResult } from '../src/lib/auditLog.js'
test('audit events classify the activity surfaces used by the tray', () => {
assert.equal(categorizeTool('desktop_powershell'), 'command')
assert.equal(categorizeTool('desktop_read_file'), 'files')
assert.equal(categorizeTool('desktop_computer_screenshot'), 'screen')
assert.equal(categorizeTool('desktop_computer_input'), 'input')
assert.equal(categorizeTool('desktop_adb_shell'), 'devices')
assert.equal(categorizeTool('daemon.connect'), 'system')
assert.equal(categorizeTool('desktop_unknown'), 'other')
})
test('activity drilldown retains bounded command and stream evidence without sensitive inputs', () => {
const details = auditDetails(
{ script: 'Write-Output "hello"', cwd: 'C:\\work', env: { SECRET: 'hidden' }, content: 'private file body' },
{ exit_code: 0, stdout: 'hello\n', stderr: '', output: { stdout: { truncated: false } } }
)
assert.match(details.request_detail ?? '', /Write-Output/)
assert.doesNotMatch(details.request_detail ?? '', /SECRET|private file body/)
assert.equal(details.stdout, 'hello\n')
assert.equal(details.stderr, '')
assert.match(details.result_detail ?? '', /"exit_code": 0/)
})
test('audit events preserve process exit outcome separately from dispatch success', () => {
const result = { exit_code: 17, stdout: '', stderr: 'failed' }
assert.equal(resultExitCode(result), 17)
+34
View File
@@ -0,0 +1,34 @@
import assert from 'node:assert/strict'
import { EventEmitter } from 'node:events'
import test from 'node:test'
import type { TLSSocket } from 'node:tls'
import { BrokerRelaySocket } from '../src/transport/BrokerRelaySocket.js'
class FakeTlsSocket extends EventEmitter {
write(): boolean { return true }
end(): this { return this }
destroy(): this { return this }
}
test('late open listener fires after the broker socket already opened', async () => {
const socket = new BrokerRelaySocket(new FakeTlsSocket() as unknown as TLSSocket)
socket.opened()
await new Promise<void>(resolve => queueMicrotask(resolve))
let opens = 0
socket.addEventListener('open', () => { opens += 1 })
await new Promise<void>(resolve => queueMicrotask(resolve))
assert.equal(opens, 1)
})
test('listener attached before queued open fires exactly once', async () => {
const socket = new BrokerRelaySocket(new FakeTlsSocket() as unknown as TLSSocket)
let opens = 0
socket.addEventListener('open', () => { opens += 1 })
socket.opened()
await new Promise<void>(resolve => queueMicrotask(resolve))
assert.equal(opens, 1)
})

Some files were not shown because too many files have changed in this diff Show More