Skip to content

The agent that grows with you

fix(desktop): Bot Mode on a multiplexed sibling profile works over the one host socket

teknium178af0a1e9199
diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.ts
index c50a14ac02b..ef09f9fc63d 100644
--- a/apps/desktop/electron/local-gateway.test.ts
+++ b/apps/desktop/electron/local-gateway.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest'
-import { createLocalGatewayDials, ensureLocalGateway } from './local-gateway'
+import { createLocalGatewayDials, ensureLocalGateway, routedGatewayEndpoint } from './local-gateway'
test('canonical ensure cannot cross a rejected update or profile lifecycle gate', async () => {
let ran = false
@@ -111,7 +111,9 @@ test('private dial credential is one-use and bound to the requesting native wind
expect(url).not.toContain('private-ticket')
const details = { url, webContentsId: 8, resourceType: 'webSocket', requestHeaders: { Origin: 'http://renderer', 'Sec-WebSocket-Protocol': 'hermes-gateway-v1, hermes-gateway-ticket.private-ticket' } }
expect(dials.headers(details)).toBeNull()
- const headers = dials.headers({ ...details, webContentsId: 7 })!
+ // The dial may cross a loopback proxy that rewrites host:port but keeps the nonce.
+ const proxied = url.replace('127.0.0.1:1234', '127.0.0.1:4321')
+ const headers = dials.headers({ ...details, url: proxied, webContentsId: 7 })!
expect(headers).not.toHaveProperty('Origin')
expect(headers['Sec-WebSocket-Protocol']).toBe('hermes-gateway-v1, hermes-gateway-ticket.private-ticket')
expect(dials.headers({ ...details, webContentsId: 7 })).toBeNull()
@@ -238,3 +240,11 @@ test.skipIf(process.platform === 'win32')('a group-accessible control socket is
await fs.rm(home, { recursive: true, force: true })
}
})
+
+test('a ?profile= request on the shared host descriptor mints for the sibling profile home', () => {
+ const endpoint = { profile_id: '/h/.hermes', instance_id: 'i', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1', capabilities: [], supervisor: 'none', control_home: null }
+ expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/sessions?profile=p2', '/h/.hermes')).toMatchObject({ profile_id: '/h/.hermes/profiles/p2', control_home: '/h/.hermes' })
+ expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/sessions?profile=default', '/h/.hermes')).toBe(endpoint)
+ expect(routedGatewayEndpoint({ ...endpoint, profile_id: '/h/.hermes/profiles/p2', control_home: '/h/.hermes' }, 'http://127.0.0.1:1/x?profile=default', '/h/.hermes')).toMatchObject({ profile_id: '/h/.hermes' })
+ expect(() => routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/x?profile=../evil', '/h/.hermes')).toThrow('Invalid profile route')
+})
diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.ts
index cd2536d2d86..f3e0e40cc68 100644
--- a/apps/desktop/electron/local-gateway.ts
+++ b/apps/desktop/electron/local-gateway.ts
@@ -107,6 +107,16 @@ export async function redialLocalGateway<TEndpoint, TResult>(deps: {
}
}
+function dialNonce(url: string): string | null {
+ try {
+ const parsed = new URL(url)
+
+ return parsed.pathname === '/api/ws' ? parsed.searchParams.get('native_dial') : null
+ } catch {
+ return null
+ }
+}
+
// A one-use ticket crosses private IPC, then leaves the URL before dialing.
// Public descriptors and persisted connection state never contain credentials.
export function createLocalGatewayDials() {
@@ -117,16 +127,20 @@ export function createLocalGatewayDials() {
for (const [key, value] of pending) {if (value.expires <= Date.now()) {pending.delete(key)}}
if (pending.size >= 100) {throw new Error('Too many pending gateway dials')}
- const url = `${origin.replace(/^http/, 'ws')}/api/ws?native_dial=${crypto.randomUUID()}`
- pending.set(url, { ticket, webContentsId, expires: Date.now() + 25_000 })
+ // Keyed by the one-use nonce, not the full URL: a loopback proxy the app dials
+ // through (tests, tunnels) rewrites host:port but carries the query through.
+ const nonce = crypto.randomUUID()
+ const url = `${origin.replace(/^http/, 'ws')}/api/ws?native_dial=${nonce}`
+ pending.set(nonce, { ticket, webContentsId, expires: Date.now() + 25_000 })
return `${url}&ticket=${encodeURIComponent(ticket)}`
},
headers(details: { url: string; webContentsId?: number; resourceType: string; requestHeaders?: Record<string, string> }) {
- const grant = pending.get(details.url)
+ const nonce = dialNonce(details.url)
+ const grant = nonce ? pending.get(nonce) : undefined
- if (!grant || grant.webContentsId !== details.webContentsId || details.resourceType !== 'webSocket') {return null}
- pending.delete(details.url)
+ if (!nonce || !grant || grant.webContentsId !== details.webContentsId || details.resourceType !== 'webSocket') {return null}
+ pending.delete(nonce)
if (grant.expires <= Date.now()) {return null}
const headers = { ...details.requestHeaders }
@@ -145,12 +159,31 @@ async function privateNode(file: string, kind: 'directory' | 'socket' | 'file')
if (!valid || node.uid !== process.getuid?.() || (node.mode & 0o077)) {throw new Error('Unsafe gateway control path')}
}
-export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: GatewayEndpoint; baseUrl: string }, url: string) {
+/** The endpoint a `?profile=<name>` request is scoped to on a shared host descriptor: the same
+ * daemon, ticket minted for the sibling profile's home (`profiles/<name>` under the launch root).
+ * The gateway refuses a ticket whose profile it does not serve, so a bad name fails closed. */
+export function routedGatewayEndpoint(endpoint: GatewayEndpoint, url: string, launchHome: string): GatewayEndpoint {
+ const profile = new URL(url).searchParams.get('profile')?.trim()
+
+ if (!profile || profile === 'current') {return endpoint}
+ const own = path.basename(endpoint.profile_id)
+ const ownName = path.basename(path.dirname(endpoint.profile_id)) === 'profiles' ? own : 'default'
+
+ if (profile === ownName) {return endpoint}
+
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(profile)) {throw new Error('Invalid profile route')}
+ const root = path.basename(path.dirname(endpoint.profile_id)) === 'profiles' ? path.dirname(path.dirname(endpoint.profile_id)) : launchHome
+ const home = profile === 'default' ? root : path.join(root, 'profiles', profile)
+
+ return { ...endpoint, profile_id: home, control_home: endpoint.control_home || endpoint.profile_id }
+}
+
+export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: GatewayEndpoint; baseUrl: string }, url: string, launchHome = descriptor.gatewayEndpoint.profile_id) {
if (new URL(url).origin !== descriptor.gatewayEndpoint.api_origin || descriptor.baseUrl !== descriptor.gatewayEndpoint.api_origin) {
throw new Error('Native gateway HTTP origin mismatch')
}
- return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(descriptor.gatewayEndpoint, 'native-http') }
+ return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(routedGatewayEndpoint(descriptor.gatewayEndpoint, url, launchHome), 'native-http') }
}
let windowsTicketClient: ((endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http') => Promise<string>) | undefined
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 7f19df24554..db9a88ec6f5 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -5425,7 +5425,7 @@ function fetchJson(url, token, options: any = {}) {
async (requestState: any) => {
// Mint inside each retry: a grant authorizes exactly one HTTP request.
const nativeHeaders = options.gatewayDescriptor
- ? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url)
+ ? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url, HERMES_HOME)
: null
return new Promise((resolve, reject) => {
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 3439ec3395c..dd295b88453 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -113,11 +113,13 @@ export class CanonicalDesktopProtocol {
}
if (method === 'session.create') {
- const allowed = new Set(['request_id', 'source', 'cwd', 'model', 'toolsets', 'profile', 'cols'])
+ const allowed = new Set(['request_id', 'source', 'cwd', 'model', 'toolsets', 'profile', 'cols', 'title', 'hidden', 'follow_profile_config'])
const unsupported = Object.keys(params).filter(key => !allowed.has(key) && !(key === 'fast' && params[key] === false))
if (unsupported.length) { throw new Error(`Canonical gateway does not support explicit session options: ${unsupported.join(', ')}`) }
- const result = Object.fromEntries(Object.entries(params).filter(([key]) => ['request_id', 'cwd', 'model', 'toolsets'].includes(key)))
+ // The socket is bound to a profile already; only a sibling the host multiplexes rides as `profile`.
+ const result = Object.fromEntries(Object.entries(params).filter(([key, value]) =>
+ ['request_id', 'cwd', 'model', 'toolsets', 'title', 'hidden'].includes(key) || (key === 'profile' && value && value !== 'default')))
const key = JSON.stringify(result)
const requestId = params.request_id ?? this.creates.get(key) ?? crypto.randomUUID()
this.creates.set(key, String(requestId))
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 715a19bfc10..fd6358b02b5 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -1,5 +1,6 @@
"""Authenticated WS projection of the gateway authority; no TUI execution fallback."""
from dataclasses import asdict
+from pathlib import Path
import sqlite3
import uuid
@@ -33,8 +34,27 @@ class AuthorityConnection:
bind_native_transport(authority, self.actor, identity)
self.native_owner = identity.get('native_bootstrap') is True
self.subscriptions = {}
+ self._identity, self._operator, self._siblings = identity, operator, {}
authority.events[self.actor.transport_id] = transport
+ def _sibling_for(self, profile):
+ """Connection bound to the sibling authority a ``profile`` param names, or None for our own
+ home. One native socket serves every profile this process multiplexes (the Desktop's
+ shared-primary route); a profile nobody here serves is a mismatch, never a fallback."""
+ from hermes_cli.profiles import profile_matches_home
+ if profile_matches_home(profile, Path(self.authority.profile_id)):
+ return None
+ registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)
+ for sibling in (registry or ()):
+ if sibling is not self.authority and profile_matches_home(profile, Path(sibling.profile_id)):
+ connection = self._siblings.get(sibling.profile_id)
+ if connection is None:
+ identity = dict(self._identity, profile_id=sibling.profile_id, instance_id=sibling.instance_id)
+ connection = AuthorityConnection(sibling, self.transport, identity, operator=self._operator)
+ self._siblings[sibling.profile_id] = connection
+ return connection
+ raise RuntimeStoreError('profile_mismatch')
+
async def dispatch(self, request):
rid = request.get('id')
method = request.get('method')
@@ -43,6 +63,19 @@ class AuthorityConnection:
# Every handler indexes params as a mapping; refuse the frame before ``.get``.
return {'jsonrpc': '2.0', 'id': rid, 'error': {
'code': 4001, 'message': 'invalid_params', 'data': {'reason': 'invalid_params'}}}
+ profile = params.get('profile')
+ if isinstance(profile, str) and profile:
+ try:
+ routed = self._sibling_for(profile)
+ except RuntimeStoreError as exc:
+ return {'jsonrpc': '2.0', 'id': rid, 'error': {
+ 'code': 4001, 'message': exc.reason, 'data': {'reason': exc.reason}}}
+ if routed is not None:
+ return await routed.dispatch(request)
+ # Our own home: the scope is implicit for session verbs; group verbs validate it themselves.
+ from gateway.session_group_controls import GROUP_METHODS
+ if method not in GROUP_METHODS and method != 'profiles.list':
+ params = {key: value for key, value in params.items() if key != 'profile'}
ref = SessionRef(self.actor.profile_id, params.get('session_id', ''))
handlers = {'session.create': self.create, 'ping': self.ping, 'runtime.describe': self.describe,
'commands.catalog': self.command_catalog, 'complete.slash': self.slash_completions,
@@ -180,11 +213,20 @@ class AuthorityConnection:
# ``-c <title> --create-if-missing``: resolve-or-create is one owner step (no await
# between lookup and creation), so concurrent programmatic callers converge.
title = validate_title(params.pop('title')) if 'title' in params else None
+ # Bot Mode's forever-chat mint: born hidden from the sidebar; `follow_profile_config` is
+ # the canonical default (a local session's runtime is built from the profile's current
+ # config on every attach), so the flag is accepted for the legacy contract and implied.
+ hidden = params.pop('hidden', False)
+ params.pop('follow_profile_config', None)
+ if type(hidden) is not bool:
+ raise RuntimeStoreError('invalid_params')
ref = title and resolve_titled_session(self.authority, self.actor, title, missing_ok=True)
if not ref:
ref = create_local_session(self.authority, self.actor, params)
if title:
title_new_session(self.authority, ref, title)
+ if hidden:
+ self.authority.db.set_session_hidden(ref.session_id, True)
return await self.resume(ref, {})
async def ping(self, ref, params):
@@ -214,8 +256,26 @@ class AuthorityConnection:
if 'session:read' not in self.actor.capabilities:
raise RuntimeStoreError('permission_denied')
limit = params.get('limit', 200)
- if set(params) - {'limit'} or type(limit) is not int or not 1 <= limit <= 200:
+ if set(params) - {'limit', 'title', 'include_hidden'} or type(limit) is not int or not 1 <= limit <= 200:
raise RuntimeStoreError('invalid_params')
+ if 'title' in params:
+ # Title-as-identity lookup (the Bots roster's forever-chat registry): the same
+ # resolver `session.resume title=` uses, so a hidden canonical chat answers here
+ # instead of being re-minted. Never confirms another principal's titles.
+ from gateway.session_local_title import resolve_titled_session
+ found = resolve_titled_session(self.authority, self.actor, params['title'], missing_ok=True)
+ if found is None:
+ return {'sessions': [], 'scope': 'stored'}
+ row = self.authority.db.get_session(found.session_id) or {}
+ root = self.authority.db.get_session(
+ self.authority.db.resolve_session_by_title(params['title']) or found.session_id) or row
+ return {'sessions': [{'session_id': found.session_id, 'id': root.get('id') or found.session_id,
+ 'resolved_id': found.session_id, 'title': row.get('title') or '',
+ 'root_title': root.get('title') or '', 'source': row.get('source'),
+ 'started_at': row.get('started_at'),
+ 'message_count': row.get('message_count', 0),
+ 'running': found.session_id in self.authority.sessions}],
+ 'scope': 'stored'}
sessions = []
for sid in tuple(self.authority.sessions):
candidate = SessionRef(self.actor.profile_id, sid)
@@ -350,6 +410,9 @@ class AuthorityConnection:
params["prompt_id"], {"answer": params["answer"]}, kind="clarify")
async def close(self):
+ for sibling in self._siblings.values():
+ await sibling.close()
+ self._siblings.clear()
# Deletion may already have evicted a subscribed session; its membership died
# with it, and one retired ID must not leave the others (or the transport) attached.
for session_id, subscription in list(self.subscriptions.items()):
diff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.py
index 839b90125b0..7d3ef808d03 100644
--- a/gateway/session_group_controls.py
+++ b/gateway/session_group_controls.py
@@ -287,13 +287,34 @@ def _profiles(authority, actor, home, params):
if latest:
row['last_session'] = summary(authority.db.get_session(latest[0]))
profiles = [row]
+ seen = {home.resolve()}
+
+ def discovered(configured, target):
+ # Discovery metadata only: never a licence to read another owner's state/configuration.
+ if target.resolve() in seen:
+ return
+ seen.add(target.resolve())
+ entry = {'name': configured, 'path': str(target), 'is_default': configured == 'default',
+ 'model': '', 'provider': '', 'description': '', 'display_name': configured,
+ 'skill_count': 0}
+ meta_path = target / 'profile.yaml'
+ try:
+ meta = yaml.safe_load(meta_path.read_text(encoding='utf-8')) if meta_path.is_file() else {}
+ except (OSError, yaml.YAMLError):
+ meta = {}
+ if isinstance(meta, dict):
+ entry['display_name'] = str(meta.get('display_name') or configured)
+ if isinstance(meta.get('ui_meta'), dict):
+ entry['ui_meta'] = meta['ui_meta']
+ profiles.append(entry)
+
+ # Sibling profiles this process multiplexes: the roster lists them with the same
+ # standing as a hosted-room destination, and the client routes their sessions by name.
+ registry = getattr(getattr(authority, 'runner', None), 'session_authorities', None)
+ for sibling in (registry or ()):
+ discovered(served_profile_name(Path(sibling.profile_id)), Path(sibling.profile_id))
service = getattr(authority, 'hosted_room_service', None)
if service is not None:
for configured, target in service.profile_homes().items():
- if target != home:
- # Configured execution destinations are discovery metadata, not
- # permission to read another owner's state/configuration.
- profiles.append({'name': configured, 'path': str(target), 'is_default': False,
- 'model': '', 'provider': '', 'description': '',
- 'display_name': configured, 'skill_count': 0})
+ discovered(configured, target)
return {'profiles': profiles, 'bot_mode_protocol': True}
diff --git a/tests/gateway/test_session_group_controls.py b/tests/gateway/test_session_group_controls.py
index 708603b3b13..3ad1f354e0c 100644
--- a/tests/gateway/test_session_group_controls.py
+++ b/tests/gateway/test_session_group_controls.py
@@ -109,5 +109,5 @@ def test_profile_discovery_and_group_controls_enforce_actor_scope(tmp_path, monk
for method in ('profiles.list', 'groups.list'):
denied = await call(method, {'profile': 'foreign'})
assert denied['error']['message'] == 'profile_mismatch', denied
- assert (await call('profiles.delete'))['error']['message'] == 'invalid_params'
+ assert (await call('profiles.delete'))['error']['code'] == -32601 # unknown method, not a bad argument
asyncio.run(probe())