The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway,tui): /bg runs a background agent on the shared gateway
Teknium977e2a4ea57c
diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex f3f791e50c3..2f5e01ed457 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -113,6 +113,8 @@ class AuthorityConnection:handlers.update(shell_handlers(self))from gateway.session_tui_ops import handlers as tui_ops_handlershandlers.update(tui_ops_handlers(self))+ from gateway.session_tui_side import handlers as side_handlers+ handlers.update(side_handlers(self))from gateway.session_images import attach_bytesfrom functools import partialhandlers['image.attach_bytes'] = partial(attach_bytes, self)diff --git a/gateway/session_tui_side.py b/gateway/session_tui_side.pynew file mode 100644index 00000000000..31648283369--- /dev/null+++ b/gateway/session_tui_side.py@@ -0,0 +1,138 @@+"""Ink's ``/bg`` (``prompt.background``) on the shared owner.++The verb replies ``{task_id}`` at once and the answer lands later on the parent session's event+stream as ``background.complete`` ``{task_id, text}`` (``error: <exc>`` on failure) — the+sidecar's contract (``tui_gateway/methods_prompt.py``). The side agent is detached: never an+admission, never a FIFO turn, never a row in the parent transcript. It runs on a daemon thread+under the owning profile's scope and the session's frozen launch policy (cwd, terminal, model+route, toolsets), so a session that never ran a turn (no resident agent) works the same.+"""+from functools import partial+import contextlib+import logging+import threading+import uuid++from gateway.session_busy_controls import authorize+from hermes_state_runtime import RuntimeStoreError++logger = logging.getLogger(__name__)++# Strong references to the running side-agent threads (dropped as each one finishes).+_RUNNING = set()+_RUNTIME_KEYS = ('api_key', 'base_url', 'provider', 'requested_provider', 'api_mode', 'command', 'args',+ 'credential_pool', 'max_tokens', 'capabilities')+++def handlers(connection):+ return {'prompt.background': partial(background, connection)}+++def _admit(connection, ref, params, prefix):+ """Shared admission: ``(live, policy, text, task_id)`` or a refusal before any work starts."""+ text = params.get('text')+ if (set(params) - {'session_id', 'profile', 'text'} or not isinstance(ref.session_id, str)+ or not ref.session_id or not isinstance(text, str) or not text.strip()):+ raise RuntimeStoreError('invalid_params')+ authority = connection.authority+ if ref.session_id not in authority.sessions:+ raise RuntimeStoreError('not_found')+ authorize(connection, ref, params, 'session:submit')+ # The answer rides this connection's event subscription, like a submit's reply.+ if ref.session_id not in connection.subscriptions:+ raise RuntimeStoreError('permission_denied')+ authority._require_admission_open()+ from gateway.session_policy import policy_for_source+ live = authority.sessions[ref.session_id]+ policy = policy_for_source(authority.runner, live.source)+ if policy is None:+ raise RuntimeStoreError('permission_denied')+ return live, policy, text, f'{prefix}_{uuid.uuid4().hex[:6]}'+++def _side_scope(authority, policy, task_id):+ """The owning profile's home/secrets, the session's frozen policy, and the task's own session+ identity (approval key, HERMES_SESSION_ID) for the side agent's thread."""+ from gateway.session_authorities import owner_scope+ from gateway.session_context import clear_session_vars, set_session_vars+ from gateway.session_policy import policy_scope+ with owner_scope(authority, hydrate_secrets=True), policy_scope(policy, authority=authority):+ tokens = set_session_vars(session_key=task_id, session_id=task_id, cwd=policy.cwd)+ try:+ yield+ finally:+ clear_session_vars(tokens)+++def _resolve_runtime(authority, policy):+ """``(model, runtime)`` the session's next turn would use: its frozen policy route."""+ from gateway.run_turn_prepare import _resolve_policy_agent_runtime+ return _resolve_policy_agent_runtime(authority.runner, policy)+++def _spawn(authority, ref, task_id, event_type, body, extra=None):+ """Run ``body()`` on a daemon thread; publish its text (or ``error: <exc>``) on the session."""+ extra = extra or {}++ def run():+ try:+ text = body()+ except Exception as exc:+ logger.warning('Side agent %s failed', task_id, exc_info=True)+ text = f'error: {getattr(exc, "reason", None) or exc}'+ try:+ live = authority.sessions.get(ref.session_id)+ if live is not None:+ live.event_stream.publish(ref.session_id, {'task_id': task_id, **extra, 'text': str(text or '')},+ event_type=event_type)+ finally:+ _RUNNING.discard(thread)++ thread = threading.Thread(target=run, name=f'side-agent-{task_id}', daemon=True)+ _RUNNING.add(thread)+ thread.start()+ return {'task_id': task_id}+++async def background(connection, ref, params):+ """``/bg <prompt>``: a fresh agent on the session's route runs the prompt to completion."""+ live, policy, text, task_id = _admit(connection, ref, params, 'bg')+ authority = connection.authority+ runner = authority.runner++ def body():+ from agent.skill_utils import parse_config_string_list+ from gateway.run import _checkpoint_agent_kwargs+ from run_agent import AIAgent+ with _side_scope(authority, policy, task_id):+ model, runtime = _resolve_runtime(authority, policy)+ config = policy.config(authority)+ pr = getattr(runner, '_provider_routing', None) or {}+ refresh_fallback = getattr(runner, '_refresh_fallback_model', None)+ agent = AIAgent(+ model=model, **{key: runtime.get(key) for key in _RUNTIME_KEYS if key in runtime},+ **_checkpoint_agent_kwargs(config),+ max_iterations=policy.max_turns, quiet_mode=True, verbose_logging=False,+ enabled_toolsets=list(policy.current_toolsets(config)),+ disabled_toolsets=parse_config_string_list((config.get('agent') or {}).get('disabled_toolsets')) or None,+ reasoning_config=policy.current_reasoning_config(runner),+ service_tier=policy.current_service_tier(runner, live.route),+ request_overrides=dict(runtime.get('request_overrides') or {}),+ providers_allowed=pr.get('only'), providers_ignored=pr.get('ignore'), providers_order=pr.get('order'),+ provider_sort=pr.get('sort'), provider_require_parameters=pr.get('require_parameters', False),+ provider_data_collection=pr.get('data_collection'),+ # Its own session in the owning profile's store, like the sidecar's ``bg_*`` rows.+ session_id=task_id, platform=policy.platform, session_db=authority.db,+ fallback_model=refresh_fallback() if callable(refresh_fallback) else None,+ load_soul_identity=not policy.ignore_rules, skip_memory=policy.ignore_rules,+ side_agent=True)+ try:+ result = agent.run_conversation(user_message=text, task_id=task_id)+ finally:+ # AIAgent.close() is the owner boundary (memory, tool subprocesses, clients).+ with contextlib.suppress(Exception):+ agent.close()+ return result.get('final_response', str(result)) if isinstance(result, dict) else str(result)++ return _spawn(authority, ref, task_id, 'background.complete', body)diff --git a/tests/gateway/test_session_tui_side.py b/tests/gateway/test_session_tui_side.pynew file mode 100644index 00000000000..c7b5a9af006--- /dev/null+++ b/tests/gateway/test_session_tui_side.py@@ -0,0 +1,58 @@+"""Ink's /bg and /btw on the shared owner: a detached side agent off the session's FIFO.++On the per-TUI sidecar ``prompt.background`` / ``prompt.btw`` reply ``{task_id}`` at once and the+answer lands later on the parent session as ``background.complete`` / ``btw.complete``. The+canonical owner answered ``unknown_method``, so Ink refused both commands on the shared gateway.+"""+import asyncio+import json++import pytest++from tests.gateway.test_session_busy_controls import admissions, owner+from tests.gateway.fixtures.local_recovery_probe import rpc, websocket+++async def call_and_await_event(ws, method, event_type, **params):+ """``method``'s reply plus the ``event_type`` frame naming its task, read off one socket (the+ shared ``rpc`` helper drops every frame that is not its reply)."""+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': method, 'method': method, 'params': params}))+ reply, events = None, []+ async with asyncio.timeout(90):+ while True:+ frame = json.loads(await ws.recv())+ if frame.get('id') == method:+ reply = frame+ if 'error' in reply:+ return reply, None+ elif frame.get('method') == 'event' and frame['params'].get('type') == event_type:+ events.append(frame['params'])+ task = (reply or {}).get('result', {}).get('task_id')+ done = [e for e in events if e['payload'].get('task_id') == task]+ if task and done:+ return reply, done[0]++[email protected]("linux")+def test_background_prompt_runs_a_detached_agent_and_reports_on_the_session(tmp_path):+ with owner(tmp_path) as (home, peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ # A lazy session: no turn has run, so there is no resident agent to copy.+ sid = (await rpc(ws, 'session.create', request_id='bg', source='tui', toolsets=[]))['result']['session_id']+ reply, event = await call_and_await_event(ws, 'prompt.background', 'background.complete',+ session_id=sid, text='BG_TASK')+ task = reply.get('result', {}).get('task_id', '')+ assert task.startswith('bg_'), reply+ assert event['session_id'] == sid+ assert event['payload'] == {'task_id': task, 'text': 'CONTROL_ACK'}, event+ assert any('BG_TASK' in json.dumps(r['messages']) for r in peer.requests)+ for params, reason in [({'session_id': sid, 'text': ' '}, 'invalid_params'),+ ({'session_id': sid, 'text': 'x', 'profile': 'foreign'}, 'profile_mismatch')]:+ denied = await rpc(ws, 'prompt.background', **params)+ assert denied.get('error', {}).get('message') == reason, denied+ # Off the FIFO and out of the parent transcript: no admission, no parent rows.+ assert not admissions(home)+ resumed = (await rpc(ws, 'session.resume', session_id=sid))['result']+ assert not resumed['messages'], resumed['messages']+ asyncio.run(probe())diff --git a/ui-tui/src/__tests__/canonicalSideAgents.test.ts b/ui-tui/src/__tests__/canonicalSideAgents.test.tsnew file mode 100644index 00000000000..7d40e4c2175--- /dev/null+++ b/ui-tui/src/__tests__/canonicalSideAgents.test.ts@@ -0,0 +1,53 @@+import { beforeEach, expect, it, vi } from 'vitest'++import { createSlashHandler } from '../app/createSlashHandler.js'+import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'++// The shared (canonical) gateway serves prompt.background / prompt.btw: /bg and /btw take main's+// path there too instead of refusing with canonical.controls.notAvailable.++const flush = () => new Promise(resolve => setImmediate(resolve))++function harness() {+ const request = vi.fn(async (method: string, params: any) => {+ if (method === 'prompt.background') {+ return { task_id: 'bg_abc123' }+ }++ if (method === 'prompt.btw') {+ return { task_id: 'btw_def456' }+ }++ throw new Error(`unknown_method: ${method} ${JSON.stringify(params)}`)+ })++ const sys = vi.fn()++ const ctx = {+ slashFlightRef: { current: 0 },+ gateway: { gw: { isCanonical: true, request }, rpc: request },+ transcript: { page: vi.fn(), panel: vi.fn(), send: vi.fn(), sys, setHistoryItems: vi.fn(), trimLastExchange: (items: unknown[]) => items },+ local: { getHistoryItems: () => [], getLastUserMsg: () => '', maybeWarn: vi.fn() },+ session: { resumeById: vi.fn() },+ composer: { enqueue: vi.fn() }+ }++ return { request, slash: createSlashHandler(ctx as any), sys }+}++beforeEach(() => {+ resetUiState()+ patchUiState({ sid: 'owner', info: { model: 'm', skills: {}, tools: {}, execution_epoch: '1', execution_generation: 3 } as any })+})++it('/bg starts prompt.background on the shared gateway and tracks the task', async () => {+ const { request, slash, sys } = harness()++ slash('/bg summarize the repo')+ await flush()++ expect(request).toHaveBeenCalledWith('prompt.background', { session_id: 'owner', text: 'summarize the repo' })+ expect(sys).toHaveBeenCalledWith('bg bg_abc123 started')+ expect(sys.mock.calls.flat().join('\n')).not.toMatch(/not available/i)+ expect(getUiState().bgTasks.has('bg_abc123')).toBe(true)+})diff --git a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts b/ui-tui/src/__tests__/canonicalSlashCommands.test.tsindex ab43a024fd7..c3e307b66be 100644--- a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts+++ b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts@@ -161,7 +161,7 @@ it("/usage renders main's session totals from session.stats and /tools says whatexpect(request.mock.calls.some(([method]) => LEGACY.includes(method))).toBe(false)})-it('/status reads through the gateway; /bg and /btw refuse instead of calling sidecar-only RPCs', async () => {+it('/status reads through the gateway; /btw refuses instead of calling a sidecar-only RPC', async () => {const { page, request, slash, sys } = harness()slash('/status')@@ -169,7 +169,7 @@ it('/status reads through the gateway; /bg and /btw refuse instead of calling siexpect(request).toHaveBeenCalledWith('slash.exec', { command: 'status', session_id: 'owner' })expect(page).toHaveBeenCalledWith('Session: owner', expect.any(String))- for (const cmd of ['/bg check the logs', '/btw what was that']) {+ for (const cmd of ['/btw what was that']) {slash(cmd)}@@ -177,13 +177,13 @@ it('/status reads through the gateway; /bg and /btw refuse instead of calling siconst methods = request.mock.calls.map(([method]) => method)- for (const method of ['session.status', 'prompt.background', 'prompt.btw']) {+ for (const method of ['session.status', 'prompt.btw']) {expect(methods).not.toContain(method)}const notices = sys.mock.calls.map(([text]) => String(text))- for (const name of ['bg', 'btw']) {+ for (const name of ['btw']) {expect(notices).toContain(`/${name} is not available on the shared gateway yet`)}})diff --git a/ui-tui/src/app/slash/commands/session.ts b/ui-tui/src/app/slash/commands/session.tsindex 32c2def7a8d..7795a627bb8 100644--- a/ui-tui/src/app/slash/commands/session.ts+++ b/ui-tui/src/app/slash/commands/session.ts@@ -117,10 +117,6 @@ export const sessionCommands: SlashCommand[] = [return ctx.transcript.sys(t('slashCmd.session.bg.usage'))}- if (ctx.gateway.gw?.isCanonical) {- return ctx.transcript.sys(t('canonical.controls.notAvailable', 'bg'))- }-ctx.gateway.rpc<BackgroundStartResponse>('prompt.background', { session_id: ctx.sid, text: arg }).then(ctx.guarded<BackgroundStartResponse>(r => {if (!r.task_id) {