The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway,tui): /reload re-reads the profile .env on the shared gateway
Tekniumf25a5dfe29ee
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex af7506826fb..8d849fd510b 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4015,7 +4015,11 @@ export interface ToolsConfigureResult {reset: booleanunknown: string[]}-export type ReloadEnvParams = Record<string, never>+/** The shared owner serves ``/reload`` for one session the caller controls (``session_id``). */+export interface ReloadEnvParams {+ session_id?: string | null+ profile?: string | null+}export interface ReloadEnvResult {updated: number}diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 3aefb9f825a..c3d9c97cfdf 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -31572,7 +31572,33 @@},"ReloadEnvParams": {"additionalProperties": false,- "properties": {},+ "description": "The shared owner serves ``/reload`` for one session the caller controls (``session_id``).",+ "properties": {+ "session_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Session Id"+ },+ "profile": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Profile"+ }+ },"title": "ReloadEnvParams","type": "object"},diff --git a/gateway/session_tui_ops.py b/gateway/session_tui_ops.pyindex 7c53585e42a..50aeceb5764 100644--- a/gateway/session_tui_ops.py+++ b/gateway/session_tui_ops.py@@ -1,12 +1,12 @@-"""Ink's session utilities on the shared owner: ``/save`` (``session.save``).+"""Ink's session utilities on the shared owner: ``/save`` (``session.save``) and ``/reload``+(``reload.env``).Main's per-TUI sidecar served these from its own session table, which never holds a shared-gateway-session, so the canonical TUI refused them. Each verb here acts on one authority session (or, for-the documented process-wide ones, on this owner) and reuses main's helpers rather than re-deriving-them; blocking work runs off the loop under the owning profile's runtime scope.+session, so the canonical TUI refused them. Each verb reuses main's helpers rather than re-deriving+them. ``dispatch`` already runs every handler under the owning profile's scope (``owner_scope``) and+``asyncio.to_thread`` carries that context into the worker thread."""import asyncio-from contextlib import nullcontextfrom datetime import datetimefrom functools import partialfrom pathlib import Path@@ -16,23 +16,22 @@ from hermes_state_runtime import RuntimeStoreErrordef handlers(connection):- return {'session.save': partial(save_session, connection)}+ return {'session.save': partial(save_session, connection),+ 'reload.env': partial(reload_env, connection)}def _profile_home(authority):- """The owning profile's home, or None for a symbolic (test peer) id."""+ """The owning profile's home (a symbolic test-peer id falls back to the scoped home)."""home = Path(str(authority.profile_id))- return home if home.is_absolute() and home.is_dir() else None+ if home.is_absolute() and home.is_dir():+ return home+ from hermes_constants import get_hermes_home+ return get_hermes_home()-def _profile_scope(authority):- """Bind the owning profile's home + secrets for one off-loop call (enter it IN the thread:- ``to_thread`` copies the caller's context, so a scope entered on the loop would leak)."""- home = _profile_home(authority)- if home is None:- return nullcontext()- from gateway.run import _profile_runtime_scope- return _profile_runtime_scope(home, hydrate_secrets=False)+def _multiplexed(authority):+ """Every turn runs under a per-profile secret scope (``owner_scope``'s own predicate)."""+ return bool(getattr(getattr(authority.runner, 'config', None), 'multiplex_profiles', False))def _live_ref(connection, ref, params, fields, capability):@@ -50,25 +49,55 @@ async def save_session(connection, ref, params):authority = connection.authorityfrom gateway.session_ancillary import physical_targettarget = physical_target(authority, ref)- home = _profile_home(authority)def write():from hermes_cli.session_export import load_save_snapshot, render_session_for_save- from hermes_constants import get_hermes_homefrom hermes_state import SessionExportTooLargeError- with _profile_scope(authority):- try:- data = load_save_snapshot(authority.db, target, 'json')- except SessionExportTooLargeError as exc:- raise RuntimeStoreError('export_too_large') from exc- if not data:- raise RuntimeStoreError('not_found')- path = ((home or get_hermes_home()) / 'sessions' / 'saved'- / f'hermes_conversation_{datetime.now():%Y%m%d_%H%M%S}.json')- try:- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(render_session_for_save(data, 'json'), encoding='utf-8')- except OSError as exc:- raise RuntimeStoreError('storage_unavailable') from exc+ try:+ data = load_save_snapshot(authority.db, target, 'json')+ except SessionExportTooLargeError as exc:+ raise RuntimeStoreError('export_too_large') from exc+ if not data:+ raise RuntimeStoreError('not_found')+ path = (_profile_home(authority) / 'sessions' / 'saved'+ / f'hermes_conversation_{datetime.now():%Y%m%d_%H%M%S}.json')+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(render_session_for_save(data, 'json'), encoding='utf-8')+ except OSError as exc:+ raise RuntimeStoreError('storage_unavailable') from excreturn {'file': str(path)}return await asyncio.to_thread(write)+++async def reload_env(connection, ref, params):+ """``/reload``: re-read the profile's ``.env`` (main's ``reload.env`` / CLI ``/reload``).++ Single-profile owner: main's ``hermes_cli.config.reload_env()`` verbatim — the owner's+ ``os.environ`` is what its turns read, exactly as the TUI's own sidecar process was. Built agents+ keep their credential pool until ``/new`` (main's documented behaviour).++ Multiplexed owner: ``os.environ`` is shared by every served profile and turns never read profile+ secrets from it, so it is left alone. Each turn already re-reads ``.env`` into its own scope; what+ can be stale is the profile's external secret-source snapshot, which is re-pulled here. The count+ is the number of keys whose value in this profile's secret scope changed.+ """+ # Addressed at one session the caller controls: a sessionless frame stays refused, as it was+ # before this verb existed (a bare grant must not rewrite the owner's environment).+ _live_ref(connection, ref, params, {'session_id', 'profile'}, 'session:control')+ authority = connection.authority++ def reload():+ if not _multiplexed(authority):+ from hermes_cli.config import reload_env as reload_process_env+ return reload_process_env()+ from agent.secret_scope import build_profile_secret_scope, invalidate_env_file_cache+ from hermes_cli.env_loader import hydrate_profile_secret_sources, reset_secret_source_cache+ home = _profile_home(authority)+ before = build_profile_secret_scope(home)+ invalidate_env_file_cache(home / '.env')+ reset_secret_source_cache(home)+ hydrate_profile_secret_sources(home)+ after = build_profile_secret_scope(home)+ return sum(before.get(key) != after.get(key) for key in before.keys() | after.keys())+ return {'updated': int(await asyncio.to_thread(reload))}diff --git a/tests/gateway/test_session_process_scope.py b/tests/gateway/test_session_process_scope.pyindex ecf1fc2ff6b..55f66ddc884 100644--- a/tests/gateway/test_session_process_scope.py+++ b/tests/gateway/test_session_process_scope.py@@ -9,9 +9,9 @@ from tests.gateway.fixtures.local_recovery_probe import child_envdef test_stop_is_session_scoped_and_global_verbs_keep_the_owner_refusal(tmp_path):"""Ink ``/stop`` kills only its own session's processes (a persisted one included); another- chat's processes, persisted or not, survive. ``delegation.pause``, ``reload.env``,- and ``agents.list`` keep the authority's -32601 instead of reaching the legacy- handler that pauses every spawn or rewrites the shared environ."""+ chat's processes, persisted or not, survive. ``delegation.pause`` and ``agents.list`` keep the+ authority's -32601 instead of reaching the legacy handler that pauses every spawn; a sessionless+ ``reload.env`` is refused before it can rewrite the shared environ."""root = Path(__file__).resolve().parents[2]home, user = tmp_path / 'state', tmp_path / 'user'home.mkdir()@@ -28,6 +28,8 @@ def test_stop_is_session_scoped_and_global_verbs_keep_the_owner_refusal(tmp_pathassert receipt['sessionless_stop'] == 4001, receiptassert receipt['exited_after_sessionless'] == [True, True, False, False], receiptassert receipt['pause'] == -32601 and receipt['spawn_paused'] is False, receipt- assert receipt['reload_env'] == -32601 and receipt['environ_rewritten'] is False, receipt+ # The owner serves reload.env for one controlled session only (session_tui_ops.py); a bare frame+ # is refused before it can rewrite the shared environ.+ assert receipt['reload_env'] == 4001 and receipt['environ_rewritten'] is False, receipt# reload.mcp is now served by the owner, profile-scoped (test_desktop_process_verbs.py).assert receipt['agents_list'] == -32601, receiptdiff --git a/tests/gateway/test_session_tui_ops.py b/tests/gateway/test_session_tui_ops.pyindex 012f471a8ed..e8ddaa0d3e7 100644--- a/tests/gateway/test_session_tui_ops.py+++ b/tests/gateway/test_session_tui_ops.py@@ -29,3 +29,23 @@ def test_session_save_exports_the_stored_transcript_under_the_profile_home(tmp_p({}, 'invalid_params')]:assert (await rpc(ws, 'session.save', **params))['error']['message'] == reasonasyncio.run(probe())++[email protected]("linux")+def test_reload_env_rereads_the_profile_dotenv_for_a_controlled_session(tmp_path):+ with owner(tmp_path) as (home, _peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ sid = (await rpc(ws, 'session.create', request_id='reload', source='tui', toolsets=[]))['result']['session_id']+ env = home / '.env'+ await asyncio.to_thread(env.write_text, 'TUI_RELOAD_PROBE=one\n')+ first = await rpc(ws, 'reload.env', session_id=sid)+ assert first.get('result', {}).get('updated', 0) >= 1, first+ assert (await rpc(ws, 'reload.env', session_id=sid))['result'] == {'updated': 0}+ await asyncio.to_thread(env.write_text, 'TUI_RELOAD_PROBE=two\n')+ assert (await rpc(ws, 'reload.env', session_id=sid))['result'] == {'updated': 1}+ # A bare frame never rewrites the shared owner's environment.+ for params, reason in [({}, 'invalid_params'), ({'session_id': sid, 'profile': 'foreign'}, 'profile_mismatch'),+ ({'session_id': sid, 'force': True}, 'invalid_params')]:+ assert (await rpc(ws, 'reload.env', **params))['error']['message'] == reason+ asyncio.run(probe())diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex 9e0b8454ee4..be0477d7196 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -99,7 +99,10 @@ method("tools.configure", params=ToolsConfigureParams, result=ToolsConfigureResuclass ReloadEnvParams(Params):- pass+ """The shared owner serves ``/reload`` for one session the caller controls (``session_id``)."""++ session_id: str | None = None+ profile: str | None = Noneclass ReloadEnvResult(Result):diff --git a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts b/ui-tui/src/__tests__/canonicalSlashCommands.test.tsindex 780ad133c82..0a49f8a7326 100644--- a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts+++ b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts@@ -171,10 +171,10 @@ it('/status reads through the gateway', async () => {expect(request.mock.calls.map(([method]) => method)).not.toContain('session.status')})-it('/stop is session-scoped; process-global /agents pause, /reload-mcp and /reload refuse on the shared gateway', async () => {+it('/stop is session-scoped; process-global /agents pause and /reload-mcp refuse on the shared gateway', async () => {const { request, slash, sys } = harness()- for (const cmd of ['/stop', '/agents pause', '/reload-mcp now', '/reload']) {+ for (const cmd of ['/stop', '/agents pause', '/reload-mcp now']) {slash(cmd)}@@ -185,13 +185,13 @@ it('/stop is session-scoped; process-global /agents pause, /reload-mcp and /reloconst methods = request.mock.calls.map(([method]) => method)- for (const method of ['delegation.pause', 'reload.mcp', 'reload.env']) {+ for (const method of ['delegation.pause', 'reload.mcp']) {expect(methods).not.toContain(method)}const notices = sys.mock.calls.map(([text]) => String(text))- for (const name of ['agents pause', 'reload-mcp', 'reload']) {+ for (const name of ['agents pause', 'reload-mcp']) {expect(notices).toContain(`/${name} is not available on the shared gateway yet`)}})diff --git a/ui-tui/src/__tests__/canonicalTuiOps.test.ts b/ui-tui/src/__tests__/canonicalTuiOps.test.tsindex 33e866f0fbe..830824ca677 100644--- a/ui-tui/src/__tests__/canonicalTuiOps.test.ts+++ b/ui-tui/src/__tests__/canonicalTuiOps.test.ts@@ -55,3 +55,13 @@ it('/save calls session.save on the shared gateway and reports the saved file',expect(request).toHaveBeenCalledWith('session.save', { session_id: 'owner' })expect(notices(sys)).toContain('conversation saved to: /home/u/.hermes/sessions/saved/x.json')})++it('/reload calls reload.env for this session on the shared gateway and reports the count', async () => {+ const { request, slash, sys } = harness({ 'reload.env': { updated: 2 } })++ slash('/reload')+ await flush()++ expect(request).toHaveBeenCalledWith('reload.env', { session_id: 'owner' })+ expect(notices(sys)).toContain('reloaded .env (2 vars updated)')+})diff --git a/ui-tui/src/app/slash/commands/ops.ts b/ui-tui/src/app/slash/commands/ops.tsindex 20a4d809b8f..9329bc53e02 100644--- a/ui-tui/src/app/slash/commands/ops.ts+++ b/ui-tui/src/app/slash/commands/ops.ts@@ -152,13 +152,9 @@ export const opsCommands: SlashCommand[] = [help: 're-read ~/.hermes/.env into the running gateway (CLI parity)',name: 'reload',run: (_arg, ctx) => {- // The shared owner's environment is every profile's; it re-reads `.env` per turn itself.- if (ctx.gateway.gw?.isCanonical) {- return ctx.transcript.sys(t('canonical.controls.notAvailable', 'reload'))- }-+ // The shared gateway serves `/reload` for one session this client controls.ctx.gateway- .rpc<ReloadEnvResponse>('reload.env', {})+ .rpc<ReloadEnvResponse>('reload.env', ctx.gateway.gw?.isCanonical && ctx.sid ? { session_id: ctx.sid } : {}).then(ctx.guarded<ReloadEnvResponse>(r => {const n = Number(r.updated ?? 0)