feat: admit identified Bot Chat relay deliveries through session authority

This commit is contained in:
Teknium
2026-09-08 18:00:43 -07:00
parent 107af6fc7a
commit 998df8cc0b
4 changed files with 223 additions and 1 deletions

112
gateway/session_bot.py Normal file
View File

@@ -0,0 +1,112 @@
"""Bot Chat ingress into the existing authority FIFO; viewers never own delivery.
The mailbox is a delivery receipt, not an execution queue. A committed canonical
admission is the only consumer; unknown execution is never retried as inference.
"""
import asyncio
from pathlib import Path
from gateway.session_contract import SessionRef
from gateway.config import Platform
from gateway.platforms.event import MessageEvent
from hermes_state_runtime import RuntimeStoreError, get_session_admission
from tools.bot_live_delivery import _delivery_id, _locked, _read, _write
def _home(authority, actor, profile):
home = Path(authority.db.db_path).parent.resolve()
name = home.name if home.parent.name == 'profiles' else 'default'
if actor.profile_id != authority.profile_id or profile not in (name, 'hermes' if name == 'default' else name):
raise RuntimeStoreError('profile_mismatch')
if 'session:submit' not in actor.capabilities:
raise RuntimeStoreError('permission_denied')
return home
def _target(authority, actor):
row = authority.db.get_session_by_title('Bot Chat')
if row is None:
raise RuntimeStoreError('not_found')
tip = authority.db.get_compression_tip(row['id'])
target = authority.db.get_session(tip)
if target is None or not str(target.get('chat_id') or '').startswith('local-'):
# A legacy transcript needs an owner-side binding migration, not a new agent.
raise RuntimeStoreError('runtime_coordination_required')
ref = SessionRef(authority.profile_id, target['chat_id'])
authority.authorize(actor, ref, 'session:submit')
live = authority.sessions[ref.session_id]
entry = authority.runner.session_store.lookup_by_session_key(live.route)
if live.source.platform != Platform.LOCAL or entry is None or entry.session_id != tip:
raise RuntimeStoreError('admission_conflict')
return ref, live, entry
def _result(authority, record):
row = get_session_admission(authority.db, admission_id=record['admission_id'])
if row is None:
raise RuntimeStoreError('storage_unavailable')
status = {'queued': 'queued', 'started': 'claimed', 'unknown': 'ambiguous', 'terminal': 'ambiguous'}[row['status']]
# A crash between settlement and receipt publication is unknown, not permission
# to infer again. Never fabricate the reply from a later transcript message.
if record.get('status') in {'settled', 'failed'}:
status = record['status']
return {k: v for k, v in dict(status=status, delivery_id=record['delivery_id'],
profile_home=record['profile_home'], session_id=record['session_id'],
admission_id=record['admission_id'], reply=record.get('reply', '')).items()}
async def _record_reply(authority, home, key, future):
reply = await asyncio.shield(future)
with _locked(home) as root:
path = root / f'{key}.json'
record = _read(path)
row = get_session_admission(authority.db, admission_id=record['admission_id'])
record.update(status='settled' if row['outcome'] == 'completed' else 'failed', reply=reply or '')
_write(path, record)
async def deliver(connection, params):
authority, actor = connection.authority, connection.actor
home = _home(authority, actor, params.get('profile'))
if set(params) - {'id', 'profile', 'message'}:
raise RuntimeStoreError('invalid_params')
try:
key = _delivery_id(params.get('id'))
except ValueError as exc:
raise RuntimeStoreError('invalid_params') from exc
message = params.get('message')
if not isinstance(message, str) or not message.strip() or len(message) > 16200:
raise RuntimeStoreError('invalid_params')
authority._require_admission_open()
with _locked(home) as root:
path = root / f'{key}.json'
record = _read(path)
if record is not None and record.get('admission_id'):
if record['message'] != message or record['principal_id'] != actor.subject:
raise RuntimeStoreError('admission_conflict')
authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')
return _result(authority, record)
if record is not None:
raise RuntimeStoreError('unknown_execution')
ref, live, entry = _target(authority, actor)
event = MessageEvent(text=message, source=live.source, internal=True,
message_id='bot:' + key, metadata={'gateway_session_key': live.route,
'gateway_session_id': entry.session_id})
# Pin the physical target before committing. A process death in this
# two-store window leaves an explicit unknown record, never a new target.
record = dict(delivery_id=key, profile_home=str(home), session_id=ref.session_id,
principal_id=actor.subject, message=message, status='ambiguous')
_write(path, record)
receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, 'bot:' + key)
record.update(status='canonical', admission_id=receipt.admission_id)
_write(path, record)
if receipt.status in {'queued', 'started'}:
future = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())
task = asyncio.create_task(_record_reply(authority, home, key, future))
# Keep receipt publication independent of the requesting WebSocket.
tasks = getattr(authority, '_bot_receipt_tasks', None)
if tasks is None:
tasks = authority._bot_receipt_tasks = set()
tasks.add(task)
task.add_done_callback(tasks.discard)
return _result(authority, record)

View File

@@ -35,7 +35,7 @@ class AuthorityConnection:
'commands.catalog': self.command_catalog, 'complete.slash': self.slash_completions,
'slash.exec': self.slash_exec, 'command.dispatch': self.command_dispatch,
'session.list': self.list_sessions, 'session.info': self.info,
'session.mutate': self.mutate,
'session.mutate': self.mutate, 'bot_relay.deliver': self.bot_deliver,
'worker.register': self.worker_register, 'worker.adopt': self.worker_adopt,
'worker.persist': self.worker_persist,
'setup.status': self.setup_status, 'setup.runtime_check': self.setup_runtime_check,
@@ -55,6 +55,10 @@ class AuthorityConnection:
return {'jsonrpc': '2.0', 'id': rid, 'error': {
'code': 5001, 'message': 'storage_unavailable', 'data': {'reason': 'storage_unavailable'}}}
async def bot_deliver(self, ref, params):
from gateway.session_bot import deliver
return await deliver(self, params)
async def worker_register(self, ref, params):
from gateway.session_worker import worker_request
return await worker_request(self, ref, params, operation='register')

View File

@@ -0,0 +1,90 @@
"""Authenticated production WebSockets and loopback-only inference."""
import asyncio
from http.server import ThreadingHTTPServer
import json
import os
from pathlib import Path
import sqlite3
import sys
import threading
from automation_peer import Model
from local_recovery_probe import daemon, websocket, rpc
def probe(base):
root = Path(__file__).resolve().parents[3]
home, user = base / 'state', base / 'user'
home.mkdir(); user.mkdir()
model = ThreadingHTTPServer(('127.0.0.1', 0), Model)
model.requests = []
model.blocked, model.release = threading.Event(), threading.Event()
threading.Thread(target=model.serve_forever, daemon=True).start()
url = f'http://127.0.0.1:{model.server_port}/v1'
(home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},
'model': {'provider': 'custom', 'default': 'local-fixture', 'base_url': url},
'auxiliary': {'title_generation': {'enabled': False}}}))
env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}
env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)
def rows():
with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
db.row_factory = sqlite3.Row
return [dict(r) for r in db.execute('SELECT * FROM session_admissions ORDER BY seq')]
async def wait(predicate):
async with asyncio.timeout(30):
while not predicate():
await asyncio.sleep(.05)
async def run(desc):
async with websocket(home, desc) as ws:
created = await rpc(ws, 'session.create', request_id='bot', source='gui', toolsets=[], cwd=str(home))
sid = created['result']['session_id']
renamed = await rpc(ws, 'session.mutate', session_id=sid, request_id='name',
expected_revision=created['result']['revision'], operation='rename', payload={'title': 'Bot Chat'})
assert 'result' in renamed, renamed
await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='WARM_BOT')
await wait(lambda: rows()[0]['status'] == 'terminal')
await rpc(ws, 'prompt.submit', session_id=sid, input_id='hold', text='HOLD_AUTOMATION')
assert await asyncio.to_thread(model.blocked.wait, 20)
params = {'id': 'a' * 32, 'profile': 'default', 'message': '[Message from @sender] BOT_DM_ONCE'}
wrong = await rpc(ws, 'bot_relay.deliver', **{**params, 'profile': 'wrong-profile'})
assert wrong['error']['message'] == 'profile_mismatch', wrong
# Discard an actual response at the socket boundary before reconnecting.
await ws.send(json.dumps({'id': 'lost-ack', 'method': 'bot_relay.deliver', 'params': params}))
await wait(lambda: any('BOT_DM_ONCE' in r['payload_json'] for r in rows()))
async with websocket(home, desc) as observer:
assert 'result' in await rpc(observer, 'session.resume', session_id=sid)
retry = await rpc(observer, 'bot_relay.deliver', **params)
assert 'result' in retry, retry
assert retry['result']['status'] == 'queued', retry
conflict = await rpc(observer, 'bot_relay.deliver', **{**params, 'message': 'CHANGED'})
assert conflict['error']['message'] == 'admission_conflict', conflict
bot = [r for r in rows() if 'BOT_DM_ONCE' in r['payload_json']]
assert len(bot) == 1 and bot[0]['target_session_id'] == sid and bot[0]['status'] == 'queued', bot
model.release.set()
await wait(lambda: all(r['status'] == 'terminal' for r in rows()))
settled = await rpc(observer, 'bot_relay.deliver', **params)
assert settled['result']['status'] == 'settled', settled
assert settled['result']['reply'] == 'AUTOMATION_ACK', settled
texts = [next((m.get('content', '') for m in reversed(r['messages']) if m['role'] == 'user'), '')
for r in model.requests if r.get('messages')]
assert sum('BOT_DM_ONCE' in str(t) for t in texts) == 1, texts
print(json.dumps({'ledger': rows(), 'inputs': texts, 'lost_ack': True, 'same_target': sid}))
try:
with daemon(root, home, env, barrier=False) as (proc, desc):
try:
asyncio.run(run(desc))
print(json.dumps({'ordinary_daemon_pid': proc.pid}))
except BaseException:
print((home / 'restart.log').read_text()[-10000:], file=sys.stderr)
raise
finally:
model.release.set(); model.shutdown(); model.server_close()
if __name__ == '__main__':
probe(Path(sys.argv[1]))

View File

@@ -0,0 +1,16 @@
"""Bot relay uses the ordinary daemon's durable FIFO, not an attached viewer."""
import os
from pathlib import Path
import subprocess
import sys
def test_bot_delivery_busy_retry_keeps_exact_target(tmp_path):
root = Path(__file__).resolve().parents[2]
env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}
env['PYTHONPATH'] = str(root)
proc = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/bot_authority_peer.py'),
str(tmp_path)], cwd=root, env=env, stdin=subprocess.DEVNULL,
capture_output=True, text=True, timeout=150)
assert proc.returncode == 0, proc.stdout + proc.stderr
print(proc.stdout)