The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway,tui): /btw answers side questions on the shared gateway
Teknium92bbaff3b12d
diff --git a/gateway/session_tui_side.py b/gateway/session_tui_side.pyindex 31648283369..49613709cc9 100644--- a/gateway/session_tui_side.py+++ b/gateway/session_tui_side.py@@ -1,9 +1,10 @@-"""Ink's ``/bg`` (``prompt.background``) on the shared owner.+"""Ink's ``/bg`` (``prompt.background``) and ``/btw`` (``prompt.btw``) 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+Each verb replies ``{task_id}`` at once and the answer lands later on the parent session's event+stream as ``background.complete`` ``{task_id, text}`` / ``btw.complete`` ``{task_id, question,+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 threadunder the owning profile's scope and the session's frozen launch policy (cwd, terminal, modelroute, toolsets), so a session that never ran a turn (no resident agent) works the same."""@@ -25,7 +26,7 @@ _RUNTIME_KEYS = ('api_key', 'base_url', 'provider', 'requested_provider', 'api_mdef handlers(connection):- return {'prompt.background': partial(background, connection)}+ return {'prompt.background': partial(background, connection), 'prompt.btw': partial(btw, connection)}def _admit(connection, ref, params, prefix):@@ -136,3 +137,27 @@ async def background(connection, ref, params):return result.get('final_response', str(result)) if isinstance(result, dict) else str(result)return _spawn(authority, ref, task_id, 'background.complete', body)+++async def btw(connection, ref, params):+ """``/btw <question>``: a side question over a snapshot of the conversation+ (``agent/side_question.py``); the live history, FIFO and prompt cache stay untouched."""+ _live, policy, text, task_id = _admit(connection, ref, params, 'btw')+ authority = connection.authority+ # The resident agent's conversation (a cache-parity fork replays it); a session with no+ # resident agent (never ran a turn here, or evicted) answers from its stored transcript.+ agent = authority.agent(ref)+ snapshot = list(getattr(agent, '_session_messages', None) or [])+ from gateway.session_local_recovery import transcript_target+ target = None if snapshot else transcript_target(authority, ref)++ def body():+ from agent.side_question import answer_side_question+ history = snapshot or authority.db.get_messages_as_conversation(target)+ with _side_scope(authority, policy, task_id):+ model, runtime = _resolve_runtime(authority, policy)+ main_runtime = {'model': model, 'session_id': ref.session_id,+ **{key: runtime.get(key) for key in ('provider', 'base_url', 'api_key', 'api_mode')}}+ return answer_side_question(text, history, parent_agent=agent, main_runtime=main_runtime) or ''++ return _spawn(authority, ref, task_id, 'btw.complete', body, extra={'question': text})diff --git a/tests/gateway/test_session_tui_side.py b/tests/gateway/test_session_tui_side.pyindex c7b5a9af006..ec62d973406 100644--- a/tests/gateway/test_session_tui_side.py+++ b/tests/gateway/test_session_tui_side.py@@ -9,7 +9,7 @@ import jsonimport pytest-from tests.gateway.test_session_busy_controls import admissions, owner+from tests.gateway.test_session_busy_controls import admissions, owner, settledfrom tests.gateway.fixtures.local_recovery_probe import rpc, websocket@@ -56,3 +56,36 @@ def test_background_prompt_runs_a_detached_agent_and_reports_on_the_session(tmp_resumed = (await rpc(ws, 'session.resume', session_id=sid))['result']assert not resumed['messages'], resumed['messages']asyncio.run(probe())++[email protected]("linux")+def test_btw_answers_over_a_snapshot_without_touching_the_conversation(tmp_path):+ with owner(tmp_path) as (home, peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ # Lazy session (no resident agent): the stored transcript is the snapshot.+ lazy = (await rpc(ws, 'session.create', request_id='lazy', source='tui', toolsets=[]))['result']['session_id']+ reply, event = await call_and_await_event(ws, 'prompt.btw', 'btw.complete',+ session_id=lazy, text='LAZY_SIDE')+ task = reply.get('result', {}).get('task_id', '')+ assert task.startswith('btw_'), reply+ assert event['payload'] == {'task_id': task, 'question': 'LAZY_SIDE', 'text': 'CONTROL_ACK'}, event+ # A session that ran a turn: the resident agent's conversation is the snapshot.+ sid = (await rpc(ws, 'session.create', request_id='btw', source='tui', toolsets=[]))['result']['session_id']+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='WARM_TURN')+ await settled(home)+ before = (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']+ peer.requests.clear()+ reply, event = await call_and_await_event(ws, 'prompt.btw', 'btw.complete',+ session_id=sid, text='SIDE_QUESTION')+ task = reply['result']['task_id']+ assert event['session_id'] == sid+ assert event['payload'] == {'task_id': task, 'question': 'SIDE_QUESTION', 'text': 'CONTROL_ACK'}, event+ side = [r for r in peer.requests if 'SIDE_QUESTION' in json.dumps(r['messages'])]+ assert side and 'WARM_TURN' in json.dumps(side[0]['messages']), peer.requests+ denied = await rpc(ws, 'prompt.btw', session_id=sid, text='')+ assert denied.get('error', {}).get('message') == 'invalid_params', denied+ # History, FIFO and transcript stay untouched.+ assert [r[0] for r in admissions(home)] == ['warm']+ assert (await rpc(ws, 'session.resume', session_id=sid))['result']['messages'] == before+ asyncio.run(probe())diff --git a/ui-tui/src/__tests__/canonicalSideAgents.test.ts b/ui-tui/src/__tests__/canonicalSideAgents.test.tsindex 7d40e4c2175..1765812ed07 100644--- a/ui-tui/src/__tests__/canonicalSideAgents.test.ts+++ b/ui-tui/src/__tests__/canonicalSideAgents.test.ts@@ -51,3 +51,14 @@ it('/bg starts prompt.background on the shared gateway and tracks the task', asyexpect(sys.mock.calls.flat().join('\n')).not.toMatch(/not available/i)expect(getUiState().bgTasks.has('bg_abc123')).toBe(true)})++it('/btw asks prompt.btw on the shared gateway and announces the task', async () => {+ const { request, slash, sys } = harness()++ slash('/btw what was that error')+ await flush()++ expect(request).toHaveBeenCalledWith('prompt.btw', { session_id: 'owner', text: 'what was that error' })+ expect(sys).toHaveBeenCalledWith('btw btw_def456 — answering from a conversation snapshot')+ expect(sys.mock.calls.flat().join('\n')).not.toMatch(/not available/i)+})diff --git a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts b/ui-tui/src/__tests__/canonicalSlashCommands.test.tsindex c3e307b66be..780ad133c82 100644--- a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts+++ b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts@@ -161,31 +161,14 @@ 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; /btw refuses instead of calling a sidecar-only RPC', async () => {- const { page, request, slash, sys } = harness()+it('/status reads through the gateway', async () => {+ const { page, request, slash } = harness()slash('/status')await flush()expect(request).toHaveBeenCalledWith('slash.exec', { command: 'status', session_id: 'owner' })expect(page).toHaveBeenCalledWith('Session: owner', expect.any(String))-- for (const cmd of ['/btw what was that']) {- slash(cmd)- }-- await flush()-- const methods = request.mock.calls.map(([method]) => method)-- 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 ['btw']) {- expect(notices).toContain(`/${name} is not available on the shared gateway yet`)- }+ 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 () => {diff --git a/ui-tui/src/app/slash/commands/session.ts b/ui-tui/src/app/slash/commands/session.tsindex 7795a627bb8..2721ca7ad97 100644--- a/ui-tui/src/app/slash/commands/session.ts+++ b/ui-tui/src/app/slash/commands/session.ts@@ -138,10 +138,6 @@ export const sessionCommands: SlashCommand[] = [return ctx.transcript.sys(t('slashCmd.session.btw.usage'))}- if (ctx.gateway.gw?.isCanonical) {- return ctx.transcript.sys(t('canonical.controls.notAvailable', 'btw'))- }-ctx.gateway.rpc<BackgroundStartResponse>('prompt.btw', { session_id: ctx.sid, text: arg }).then(ctx.guarded<BackgroundStartResponse>(r => {if (!r.task_id) {