The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway,tui): /agents pause|resume toggles the spawn gate on the shared gateway
Tekniumf7ad55c0166e
diff --git a/gateway/session_tui_ops.py b/gateway/session_tui_ops.pyindex 50aeceb5764..da170a6387e 100644--- a/gateway/session_tui_ops.py+++ b/gateway/session_tui_ops.py@@ -1,5 +1,5 @@-"""Ink's session utilities on the shared owner: ``/save`` (``session.save``) and ``/reload``-(``reload.env``).+"""Ink's session utilities on the shared owner: ``/save`` (``session.save``), ``/reload``+(``reload.env``) and ``/agents pause|resume`` (``delegation.pause``).Main's per-TUI sidecar served these from its own session table, which never holds a shared-gatewaysession, so the canonical TUI refused them. Each verb reuses main's helpers rather than re-deriving@@ -17,7 +17,8 @@ from hermes_state_runtime import RuntimeStoreErrordef handlers(connection):return {'session.save': partial(save_session, connection),- 'reload.env': partial(reload_env, connection)}+ 'reload.env': partial(reload_env, connection),+ 'delegation.pause': partial(pause_delegation, connection)}def _profile_home(authority):@@ -101,3 +102,30 @@ async def reload_env(connection, ref, params):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))}+++async def pause_delegation(connection, ref, params):+ """``/agents pause|resume`` and the overlay's ``p``: main's ``delegation.pause`` — block or+ unblock NEW ``delegate_task`` spawns; running children keep going.++ The gate (``tools.delegate_tool_registry``) is process-wide, as it was in main's sidecar (a+ TUI's sidecar served one TUI, but its gate covered every agent in that process). On the shared+ owner it therefore covers every chat this gateway runs, which is what an operator's kill switch+ is for; ``delegation.status`` reports the same flag to every client."""+ paused = params.get('paused', True)+ if set(params) - {'paused', 'profile', 'session_id'} or type(paused) is not bool:+ raise RuntimeStoreError('invalid_params')+ if ref.session_id:+ authorize(connection, ref, params, 'session:control')+ else:+ if 'session:control' not in connection.actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ profile = params.get('profile')+ if profile is not None and not isinstance(profile, str):+ raise RuntimeStoreError('invalid_params')+ if profile:+ from hermes_cli.profiles import profile_matches_home+ if not profile_matches_home(profile, Path(connection.authority.profile_id)):+ raise RuntimeStoreError('profile_mismatch')+ from tools.delegate_tool_registry import set_spawn_paused+ return {'paused': set_spawn_paused(paused)}diff --git a/tests/gateway/test_session_process_scope.py b/tests/gateway/test_session_process_scope.pyindex 55f66ddc884..e8c0a2c1e1a 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`` 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."""+ chat's processes, persisted or not, survive. ``agents.list`` keeps the authority's -32601; a+ sessionless ``reload.env`` is refused before it can rewrite the shared environ; the owner serves+ ``delegation.pause`` itself (main's process-wide spawn gate)."""root = Path(__file__).resolve().parents[2]home, user = tmp_path / 'state', tmp_path / 'user'home.mkdir()@@ -27,7 +27,8 @@ def test_stop_is_session_scoped_and_global_verbs_keep_the_owner_refusal(tmp_pathassert receipt['exited'] == [True, True, False, False], receiptassert receipt['sessionless_stop'] == 4001, receiptassert receipt['exited_after_sessionless'] == [True, True, False, False], receipt- assert receipt['pause'] == -32601 and receipt['spawn_paused'] is False, receipt+ # delegation.pause is the owner's own verb now (session_tui_ops.py): main's operator kill switch.+ assert receipt['pause'] is None and receipt['spawn_paused'] is True, 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, receiptdiff --git a/tests/gateway/test_session_tui_ops.py b/tests/gateway/test_session_tui_ops.pyindex e8ddaa0d3e7..d39d512997b 100644--- a/tests/gateway/test_session_tui_ops.py+++ b/tests/gateway/test_session_tui_ops.py@@ -49,3 +49,21 @@ def test_reload_env_rereads_the_profile_dotenv_for_a_controlled_session(tmp_path({'session_id': sid, 'force': True}, 'invalid_params')]:assert (await rpc(ws, 'reload.env', **params))['error']['message'] == reasonasyncio.run(probe())++[email protected]("linux")+def test_delegation_pause_toggles_the_spawn_gate_and_status_reports_it(tmp_path):+ with owner(tmp_path) as (home, _peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ await rpc(ws, 'session.create', request_id='pause', source='tui', toolsets=[])+ paused = await rpc(ws, 'delegation.pause', paused=True)+ assert paused.get('result') == {'paused': True}, paused+ assert (await rpc(ws, 'delegation.status'))['result']['paused'] is True+ assert (await rpc(ws, 'delegation.pause', paused=False))['result'] == {'paused': False}+ assert (await rpc(ws, 'delegation.status'))['result']['paused'] is False+ for params, reason in [({'paused': 'yes'}, 'invalid_params'), ({'paused': True, 'profile': 'foreign'},+ 'profile_mismatch')]:+ assert (await rpc(ws, 'delegation.pause', **params))['error']['message'] == reason+ assert (await rpc(ws, 'delegation.status'))['result']['paused'] is False+ asyncio.run(probe())diff --git a/tui_gateway/ws_legacy_fallback.py b/tui_gateway/ws_legacy_fallback.pyindex e17299c79b1..491645aa55d 100644--- a/tui_gateway/ws_legacy_fallback.py+++ b/tui_gateway/ws_legacy_fallback.py@@ -40,7 +40,9 @@ _SESSION_FALLBACK_ALLOWED = frozenset({# ``delegation.pause`` = the global spawn gate, ``reload.mcp`` = tear down and rediscover every MCP# server, ``reload.env`` = rewrite ``os.environ`` from the launch profile's ``.env``, ``agents.list``# = every chat's process commands. The owner serves the session-scoped ``process.stop`` itself-# (``gateway/session_ancillary.py``); ``process.kill`` stays: its handler is already session-scoped.+# (``gateway/session_ancillary.py``), and ``reload.env`` / ``delegation.pause`` with owner-side rules+# (``gateway/session_tui_ops.py``); listing them here keeps the sidecar handler unreachable.+# ``process.kill`` stays: its handler is already session-scoped._PROCESS_GLOBAL = frozenset({"process.stop", "delegation.pause", "reload.mcp", "reload.env", "agents.list"})# Process-global ACTIONS of a verb whose other actions are fine on the shared owner (the gate above is# method-level, and refusing the whole verb turns its safe actions into the client's -32601 version-skewdiff --git a/ui-tui/src/__tests__/canonicalSidecarSessionVerbs.test.tsx b/ui-tui/src/__tests__/canonicalSidecarSessionVerbs.test.tsxindex 88744ae1ef1..148b35da97e 100644--- a/ui-tui/src/__tests__/canonicalSidecarSessionVerbs.test.tsx+++ b/ui-tui/src/__tests__/canonicalSidecarSessionVerbs.test.tsx@@ -35,7 +35,7 @@ const sidecarCalls = (request: ReturnType<typeof vi.fn>) =>afterEach(() => resetUiState())-async function overlayKey(gw: GatewayClient, key: string) {+async function overlayKey(gw: GatewayClient, key: string, expected = '/agents kill is not available on the shared gateway yet') {patchUiState({ sid: 'owner' })applyAgentSnapshot('owner', {delegations: [],@@ -61,7 +61,7 @@ async function overlayKey(gw: GatewayClient, key: string) {try {await vi.waitFor(() => expect(frame).toContain('child'))stdin.write(key)- await vi.waitFor(() => expect(frame).toContain('/agents kill is not available on the shared gateway yet'))+ await vi.waitFor(() => expect(frame).toContain(expected))} finally {view.unmount()view.cleanup()@@ -115,6 +115,15 @@ const SITES: [string, () => Promise<void>][] = [expect(sidecarCalls(request)).toEqual([])}],+ [+ 'agentsOverlay::togglePause (p) is the owner\'s delegation.pause',+ async () => {+ const { gw, request } = owner(method => (method === 'delegation.pause' ? { paused: true } : {}))+ await overlayKey(gw, 'p', 'spawning paused')+ expect(request).toHaveBeenCalledWith('delegation.pause', { paused: true })+ expect(sidecarCalls(request)).toEqual([])+ }+ ],['useMainApp::live-session poll (status-bar title + count)',async () => {diff --git a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts b/ui-tui/src/__tests__/canonicalSlashCommands.test.tsindex 0a49f8a7326..41cd81364df 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 and /reload-mcp refuse on the shared gateway', async () => {+it('/stop is session-scoped; process-global /reload-mcp refuses on the shared gateway', async () => {const { request, slash, sys } = harness()- for (const cmd of ['/stop', '/agents pause', '/reload-mcp now']) {+ for (const cmd of ['/stop', '/reload-mcp now']) {slash(cmd)}@@ -185,13 +185,13 @@ it('/stop is session-scoped; process-global /agents pause and /reload-mcp refuseconst methods = request.mock.calls.map(([method]) => method)- for (const method of ['delegation.pause', 'reload.mcp']) {+ for (const method of ['reload.mcp']) {expect(methods).not.toContain(method)}const notices = sys.mock.calls.map(([text]) => String(text))- for (const name of ['agents pause', 'reload-mcp']) {+ for (const name of ['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 830824ca677..b28e17afcd1 100644--- a/ui-tui/src/__tests__/canonicalTuiOps.test.ts+++ b/ui-tui/src/__tests__/canonicalTuiOps.test.ts@@ -65,3 +65,19 @@ it('/reload calls reload.env for this session on the shared gateway and reportsexpect(request).toHaveBeenCalledWith('reload.env', { session_id: 'owner' })expect(notices(sys)).toContain('reloaded .env (2 vars updated)')})++it('/agents pause and resume call delegation.pause on the shared gateway with main\'s notices', async () => {+ const { request, slash, sys } = harness({ 'delegation.pause': { paused: true } })++ slash('/agents pause')+ await flush()++ expect(request).toHaveBeenCalledWith('delegation.pause', { paused: true })++ request.mockImplementation(async () => ({ paused: false }))+ slash('/agents resume')+ await flush()++ expect(request).toHaveBeenCalledWith('delegation.pause', { paused: false })+ expect(notices(sys)).toEqual(['delegation · paused', 'delegation · resumed'])+})diff --git a/ui-tui/src/app/slash/commands/ops.ts b/ui-tui/src/app/slash/commands/ops.tsindex 9329bc53e02..a52d25db777 100644--- a/ui-tui/src/app/slash/commands/ops.ts+++ b/ui-tui/src/app/slash/commands/ops.ts@@ -352,11 +352,6 @@ export const opsCommands: SlashCommand[] = [// explicit subcommands skip the overlay and act directly so scripts and// multi-step flows can drive it without entering interactive mode.if (sub === 'pause' || sub === 'resume' || sub === 'unpause') {- // The spawn gate is process-global: on the shared owner it would pause every chat.- if (ctx.gateway.gw?.isCanonical) {- return ctx.transcript.sys(t('canonical.controls.notAvailable', `agents ${sub}`))- }-const paused = sub === 'pause'ctx.gateway.gw.request<DelegationPauseResponse>('delegation.pause', { paused })diff --git a/ui-tui/src/components/agentsOverlay.tsx b/ui-tui/src/components/agentsOverlay.tsxindex c1e4db3be27..71fbaf3877c 100644--- a/ui-tui/src/components/agentsOverlay.tsx+++ b/ui-tui/src/components/agentsOverlay.tsx@@ -794,11 +794,6 @@ export function AgentsOverlay({ gw, initialHistoryIndex = 0, onClose, t }: Agentconst togglePause = () =>guardLive(() => {- // The spawn gate is process-global: on the shared owner it would pause every chat.- if (gw.isCanonical) {- return setFlash(messages().canonical.controls.notAvailable('agents pause'))- }-gw.request<DelegationPauseResponse>('delegation.pause', { paused: !delegation.paused }).then(raw => {const r = asRpcResult<DelegationPauseResponse>(raw)