The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a Bot Chat DM refused while another writer holds the chat is a definite no-send
unsupportedpastelsbe842aa2fd60
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 5a1b20b922f..6f1889a8b01 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -6689,6 +6689,7 @@ export interface CanonicalRpcMethods {'a2a.forward': { params: A2aForwardParams; result: A2aForwardResult }'approval.respond': { params: CanonicalApprovalParams; result: PromptResponseResult }'bot_relay.deliver': { params: CanonicalBotDeliverParams; result: CanonicalBotDeliverResult }+ 'bot_relay.settle': { params: CanonicalBotDeliverParams; result: CanonicalBotDeliverResult }/** Lock one answer of the owner's batch clarify request (editable until every question is locked); only a viewer attached to that session with session:respond may lock. */'clarify.lock': { params: ClarifyLockParams; result: ClarifyLockResult }/** Generation-fenced answer to a pending clarify prompt (empty answer = skipped). */@@ -6762,6 +6763,7 @@ export const CANONICAL_RPC_METHODS = ['a2a.forward','approval.respond','bot_relay.deliver',+ 'bot_relay.settle','clarify.lock','clarify.respond','command.observe',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 5c5208842a1..e5a81d10b6d 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -46733,6 +46733,24 @@}}},+ {+ "name": "bot_relay.settle",+ "summary": "",+ "params": [+ {+ "name": "params",+ "schema": {+ "$ref": "#/components/schemas/CanonicalBotDeliverParams"+ }+ }+ ],+ "result": {+ "name": "result",+ "schema": {+ "$ref": "#/components/schemas/CanonicalBotDeliverResult"+ }+ }+ },{"name": "clarify.lock","summary": "Lock one answer of the owner's batch clarify request (editable until every question is locked); only a viewer attached to that session with session:respond may lock.",diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 57f7aa47790..96996b40e31 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -621,8 +621,9 @@ def _require_same_delivery(record, actor, message, author, category):raise RuntimeStoreError('admission_conflict')-async def _deliver(connection, params):- authority, actor = connection.authority, connection.actor+def _delivery_params(authority, actor, params):+ """``(home, key, message, author, category)`` of one ``deliver``/``settle`` request: the+ delivery's full identity, validated the same way for both verbs."""home = _home(authority, actor, params.get('profile'))if set(params) - {'id', 'profile', 'message', 'session_id', 'author', 'notification_category'}:raise RuntimeStoreError('invalid_params')@@ -643,33 +644,116 @@ async def _deliver(connection, params):author = parse_turn_author(params.get('author'))if params.get('author') is not None and (not isinstance(params['author'], dict) or author is None):raise RuntimeStoreError('invalid_params')+ return home, key, message, author, category+++def _refused_answer(record):+ return {k: record[k] for k in ('status', 'refused', 'delivery_id', 'profile_home', 'session_id',+ 'message', 'reply', 'error', 'reason')}+++async def _deliver(connection, params):+ authority, actor = connection.authority, connection.actor+ home, key, message, author, category = _delivery_params(authority, actor, params)authority._require_admission_open()async with mailbox_lock(authority):root, record = await read_receipt(home, key)path = root / f'{key}.json'- if record is not None and record.get('admission_id'):- _require_same_delivery(record, actor, message, author, category)- authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')- await _maybe_retry(authority, home, path, record)- return await _publish_result(authority, home, record)- await _migrate(authority, actor, home, root)- _, record = await read_receipt(home, key)if record is not None and record.get('admission_id'):_require_same_delivery(record, actor, message, author, category)authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')await _maybe_retry(authority, home, path, record)return await _publish_result(authority, home, record)if record is not None and record.get('refused') is True:+ # A terminal disposition (``refuse_pin``, ``settle``) is the id's answer for good._require_same_delivery(record, actor, message, author, category)- return {k: record[k] for k in ('status', 'refused', 'delivery_id', 'profile_home', 'session_id',- 'message', 'reply', 'error', 'reason')}- if record is not None:+ return _refused_answer(record)+ try:+ await _migrate(authority, actor, home, root)+ _, record = await read_receipt(home, key)+ if record is not None and record.get('admission_id'):+ _require_same_delivery(record, actor, message, author, category)+ authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')+ await _maybe_retry(authority, home, path, record)+ return await _publish_result(authority, home, record)+ if record is not None and record.get('refused') is True:+ _require_same_delivery(record, actor, message, author, category)+ return _refused_answer(record)+ if record is not None:+ raise RuntimeStoreError('unknown_execution')+ ref, live, entry = await _target(authority, actor)+ if params.get('session_id', entry.session_id) != entry.session_id:+ raise RuntimeStoreError('admission_conflict')+ return await _admit(authority, actor, home, root, key, message, ref, live, entry, author=author,+ notification_category=category)+ except RuntimeStoreError as exc:+ raise await _held_by_another_writer(home, key, exc) or exc+++async def settle(connection, params):+ from gateway.session_runtime_workers import track_mutation+ return await asyncio.shield(track_mutation(connection.authority, _settle(connection, params)))+++async def _settle(connection, params):+ """Finalize a delivery the sender was told may not have been admitted: under the mailbox lock+ every ``_admit`` holds, either settle the id as never sent or answer with what it already is.++ A ``deliver`` refusal marked ``admitted=False`` proves absence only while that request held+ the lock; a same-id attempt may admit right after. The sender calls this before it says "NOT+ sent": with no receipt and no admission row for ``bot:<id>``, a terminal ``refused`` receipt+ bound to the full identity is written, and every later ``deliver`` of the id answers with it+ instead of admitting. An admitted id gets its receipt; an in-flight pin stays unknown. Only the+ Bot DM tool calls this, so cron's same-id retries of a refusal are unchanged."""+ authority, actor = connection.authority, connection.actor+ home, key, message, author, category = _delivery_params(authority, actor, params)+ async with mailbox_lock(authority):+ _, record = await read_receipt(home, key)+ if record is None:+ record = _not_sent_record(authority, actor, home, key, message, author, category)+ await write_receipt(home, record)+ logging.getLogger(__name__).info('Bot Chat delivery %s settled as not sent (%s)', key, record['reason'])+ _require_same_delivery(record, actor, message, author, category)+ if record.get('refused') is True:+ return _refused_answer(record)+ if not record.get('admission_id'):raise RuntimeStoreError('unknown_execution')- ref, live, entry = await _target(authority, actor)- if params.get('session_id', entry.session_id) != entry.session_id:- raise RuntimeStoreError('admission_conflict')- return await _admit(authority, actor, home, root, key, message, ref, live, entry, author=author,- notification_category=category)+ authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')+ return await _publish_result(authority, home, record)+++def _not_sent_record(authority, actor, home, key, message, author, category):+ """The never-admitted id's terminal receipt, in ``refuse_pin``'s shape. Refuses (unknown) when+ the FIFO holds a ``bot:<id>`` row anyway or there is no Bot Chat to name."""+ with authority.db._read_ctx() as conn:+ admitted = conn.execute('SELECT 1 FROM session_admissions WHERE request_id=?', ('bot:' + key,)).fetchone()+ row = authority.db.get_session_by_title('Bot Chat')+ if admitted is not None or row is None:+ raise RuntimeStoreError('unknown_execution')+ from gateway.session_automation import automation_notification_metadata+ record = dict(delivery_id=key, profile_home=str(home), session_id=authority.db.get_compression_tip(row['id']),+ principal_id=actor.subject, message=message, status='failed', refused=True, reply='',+ error='Bot Chat is held by another session writer', reason='runtime_coordination_required')+ record.update(automation_notification_metadata({'notification_category': category}))+ if author is not None:+ record['author'] = dict(author)+ return record+++async def _held_by_another_writer(home, key, exc):+ """The settleable form of a ``runtime_coordination_required`` refusal, or None.++ Another session writer holds the chat (a pre-authority Desktop backend's lease on a legacy Bot+ Chat, a live CLI). Nothing was admitted under this id when it still has no receipt: ``_admit``+ pins one before it admits and withdraws it only when nothing committed. That holds only while+ this request has the lock, so ``admitted=False`` is a hint, not the verdict: the sender asks+ ``settle`` before it reports a no-send. Any other refusal keeps its unknown outcome."""+ if exc.reason != 'runtime_coordination_required' or (await read_receipt(home, key))[1] is not None:+ return None+ held = RuntimeStoreError(exc.reason, field='session_writer',+ detail='another session writer holds the Bot Chat; nothing was admitted yet')+ held.admitted = False+ return heldasync def _admit(authority, actor, home, root, key, message, ref, live, entry, author=None, legacy=None,diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex b5d970a3cfa..81b513ee05b 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -30,6 +30,8 @@ def _refusal_data(exc: RuntimeStoreError) -> dict:for key in ('revision', 'execution_generation'):if isinstance(getattr(exc, key, None), int):data[key] = getattr(exc, key)+ if getattr(exc, 'admitted', None) is False:+ data['admitted'] = False # nothing admitted yet: the sender may finalize with ``bot_relay.settle``return data@@ -166,6 +168,7 @@ class AuthorityConnection:'slash.exec': self.slash_exec, 'command.dispatch': self.command_dispatch,'session.list': self.list_sessions, 'session.info': self.info,'session.mutate': self.mutate, 'bot_relay.deliver': self.bot_deliver,+ 'bot_relay.settle': self.bot_settle,'bot_relay.roster.sync': self.bot_roster, 'bot_relay.outbox.drain': self.bot_outbox,'bot_relay.reply': self.bot_reply, 'a2a.forward': self.a2a_forward,'kanban.run': self.kanban_run,@@ -349,6 +352,10 @@ class AuthorityConnection:from gateway.session_bot import deliverreturn await deliver(self, params)+ async def bot_settle(self, ref, params):+ from gateway.session_bot import settle+ return await settle(self, params)+async def worker_register(self, ref, params):from gateway.session_worker import worker_requestreturn await worker_request(self, ref, params, operation='register')diff --git a/tests/gateway/test_bot_dm_held_by_session_writer.py b/tests/gateway/test_bot_dm_held_by_session_writer.pynew file mode 100644index 00000000000..29aed02123e--- /dev/null+++ b/tests/gateway/test_bot_dm_held_by_session_writer.py@@ -0,0 +1,238 @@+"""A Bot Chat DM the owner refuses before any admission, because another session writer holds the+chat (a pre-#106742 Desktop backend's lease on a legacy Bot Chat), is a definite, named no-send:+the tool says the message was NOT sent, and the locally pinned intent is settled so nothing replays+it. A refusal after the owner may have admitted stays ambiguous (#134889 MSG-19)."""+import asyncio+import json+import threading+from types import SimpleNamespace++import pytest+import pytest_asyncio++from hermes_state_runtime import RuntimeStoreError, list_session_admissions++CHAT = 'old-bot-chat'+++@pytest_asyncio.fixture+async def held(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ from hermes_cli import gateway_runtime+ from hermes_cli.active_sessions import release_active_session, try_acquire_active_session+ from hermes_cli.gateway_client import rpc_error+ from hermes_state import SessionDB+ from tools import bot_live_delivery, bot_mode_dm++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ store._db = SessionDB(db_path=tmp_path / 'state.db')+ db = store._db+ # A Desktop Bot Chat from before the one-gateway runtime: adopted on its first delivery.+ db.create_session(CHAT, source='desktop', model='old', cwd=str(tmp_path))+ db.set_session_title(CHAT, 'Bot Chat')+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='fixture')+ connection = AuthorityConnection(authority, object(), {+ 'user_id': 'uid:1000', 'provider': 'local', 'profile_id': 'default', 'instance_id': 'fixture',+ 'capabilities': ['session:read', 'session:submit', 'session:create']})+ monkeypatch.setattr(connection, '_sibling_for', lambda profile: None)+ authority._native_legacy_transports = {connection.actor.transport_id: connection.actor}+ executed = []++ async def execute(authority, ref, row):+ executed.append(row['payload']['text'])+ return 'pong'++ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ loop = asyncio.get_running_loop()+ # A test may hold the next refusal on its way back to the tool (``gate``), after the owner+ # answered and released its serialization: the window a concurrent same-id attempt races.+ gate = SimpleNamespace(event=None, reached=threading.Event())++ def rpc(method):+ def call(home, params):+ # What the tool's authority client speaks: the contract-checked dispatch, then the+ # client's own refusal mapping.+ frame = asyncio.run_coroutine_threadsafe(connection.dispatch(+ {'id': 1, 'method': method, 'params': params}), loop).result()+ if 'error' in frame:+ event, gate.event = gate.event, None+ if event is not None:+ gate.reached.set()+ event.wait(30)+ raise rpc_error(frame['error'])+ return frame['result']+ return call++ monkeypatch.setattr(bot_live_delivery, 'authority_delivery', rpc('bot_relay.deliver'))+ monkeypatch.setattr(bot_live_delivery, 'authority_settle', rpc('bot_relay.settle'), raising=False)+ monkeypatch.setattr(gateway_runtime, 'discover_gateway_endpoint', lambda home, timeout: SimpleNamespace(+ state='ready', endpoint=SimpleNamespace(instance_id='fixture')))+ dm_dir = tmp_path / 'dm'+ dm_dir.mkdir(mode=0o700)+ monkeypatch.setattr(bot_mode_dm, '_dm_dir', lambda: dm_dir)+ monkeypatch.setattr(bot_mode_dm, '_spawn_delivery', lambda command, label, **kwargs: '{}')+ # tui_gateway/session_lifecycle._claim_active_session_slot: the only 'desktop' lease writer.+ lease, refusal = try_acquire_active_session(session_id=CHAT, surface='desktop', config={},+ registry_home=tmp_path, metadata={'live_session_id': 'desk'}, track_liveness=True)+ assert lease is not None, refusal+ leases = [lease]++ def release():+ while leases:+ release_active_session(leases.pop())++ try:+ yield SimpleNamespace(authority=authority, db=db, home=tmp_path, dm_dir=dm_dir,+ executed=executed, release=release, gate=gate)+ finally:+ release()+ db.close()+++async def _send(held, text):+ """``message_agent``'s local send: pin the intent, then call the owner's door."""+ from tools import bot_mode_dm+ raw = await asyncio.to_thread(bot_mode_dm._start_delivery, ['hermes', '-p', 'default'], text, '@default',+ stdin_file=False, task_id=None, agent=None, profile_home=held.home)+ return json.loads(raw)+++def _admissions(held):+ return [row['request_id'] for row in list_session_admissions(held.db, session_id=CHAT, pending_only=False)]+++async def test_a_dm_refused_while_another_writer_holds_the_chat_is_a_definite_no_send(held):+ from gateway.session_bot import recover_bot_deliveries+ from tools.bot_live_delivery import read_delivery_result++ refused = await _send(held, 'ping')+ assert refused.get('reason') == 'runtime_coordination_required', refused+ assert 'status' not in refused and 'NOT sent' in refused['error'], refused+ assert 'Do not resend' not in refused['error'] and 'session' in refused['error'], refused+ # The pinned intent is settled with its payload, and the owner holds the id's terminal+ # not-sent receipt: no runner, retry or sweep can replay it.+ assert sorted(path.name for path in held.dm_dir.iterdir()) == []+ receipt = read_delivery_result(held.home, refused['delivery_id'])+ assert receipt['refused'] is True and receipt['status'] == 'failed' and not receipt.get('admission_id'), receipt+ held.release()+ await recover_bot_deliveries(held.authority)+ assert _admissions(held) == [] and held.executed == []+ # Once the other writer closes, a new send is adopted and admitted exactly once.+ sent = await _send(held, 'ping again')+ assert sent.get('status') in {'queued', 'claimed', 'settled'}, sent+ assert sent['delivery_id'] != refused['delivery_id']+ assert _admissions(held) == ['bot:' + sent['delivery_id']]+++async def test_a_refusal_after_the_owner_may_have_admitted_stays_ambiguous(held, monkeypatch):+ held.release()+ real = type(held.authority).admit_automation++ async def committed_then_refused(self, *args):+ await real(self, *args)+ raise RuntimeStoreError('runtime_coordination_required')++ monkeypatch.setattr(type(held.authority), 'admit_automation', committed_then_refused)+ held.authority._schedule = lambda ref: None+ result = await _send(held, 'ping')+ assert result.get('status') == 'ambiguous' and 'Do not resend' in result['error'], result+ assert [path.name for path in held.dm_dir.glob('*.live.json')], 'the unknown admission keeps its intent'+ assert _admissions(held) == ['bot:' + result['delivery_id']]+++def _resubmit(held, delivery_id, text):+ """A second attempt under the SAME delivery id and payload (the runner retrying the pinned+ intent), straight at the owner's door."""+ from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner+ return deliver_to_live_owner(held.home, find_canonical_live_owner(held.home), text, delivery_id=delivery_id)+++def _runner(held, dm_file):+ from tools import bot_mode_dm+ return bot_mode_dm._run_delivery(['hermes', '-p', 'default'], dm_file, stdin_file=False, profile_home=held.home)+++async def test_a_same_id_attempt_racing_a_delayed_refusal_never_coexists_with_not_sent(held):+ """The refusal leaves the owner's serialization, the lease is released and the pinned intent+ is resubmitted under the same id before the tool sees the refusal: the tool must not then say+ 'NOT sent' (and drop the intent) for a delivery the owner admitted."""+ hold = held.gate.event = threading.Event()+ first = asyncio.create_task(_send(held, 'ping'))+ assert await asyncio.to_thread(held.gate.reached.wait, 30)+ [intent] = held.dm_dir.glob('*.live.json')+ delivery_id = json.loads(intent.read_text())['delivery_id']+ held.release()+ second = await asyncio.to_thread(_resubmit, held, delivery_id, 'ping')+ assert second.get('admission_id') and _admissions(held) == ['bot:' + delivery_id], second+ hold.set() # the first refusal reaches the tool now+ answer = await first+ assert 'NOT sent' not in answer.get('error', ''), answer+ assert answer.get('status') in {'queued', 'claimed', 'settled', 'ambiguous'}, answer+ assert _admissions(held) == ['bot:' + delivery_id]+++async def test_a_not_sent_answer_is_the_delivery_ids_durable_disposition(held):+ """Once the tool said 'NOT sent', a later attempt under that id (an already-running runner+ retry) is answered with that disposition, never admitted."""+ refused = await _send(held, 'ping')+ assert 'NOT sent' in refused['error'], refused+ held.release()+ again = await asyncio.to_thread(_resubmit, held, refused['delivery_id'], 'ping')+ assert again.get('refused') is True and again['status'] == 'failed', again+ assert _admissions(held) == [] and held.executed == []+++async def test_the_runner_settles_a_held_refusal_with_its_payload(held, capsys):+ """The background runner's definite no-send removes the payload too: rerunning the same+ runner command after the writer closes can neither rebuild the intent nor admit the id."""+ from tools import bot_mode_dm+ dm_file = bot_mode_dm._write_dm_file('ping')+ assert await asyncio.to_thread(_runner, held, dm_file) == 1+ refused = json.loads(capsys.readouterr().out.strip().splitlines()[-1])+ assert 'NOT sent' in refused['error'], refused+ assert sorted(path.name for path in held.dm_dir.iterdir()) == []+ held.release()+ await asyncio.to_thread(_runner, held, dm_file)+ capsys.readouterr()+ assert _admissions(held) == [] and held.executed == []+++async def test_an_older_owner_without_the_marker_stays_ambiguous(held, monkeypatch):+ from gateway import session_bot++ async def old_owner(home, key, exc):+ return None++ monkeypatch.setattr(session_bot, '_held_by_another_writer', old_owner)+ result = await _send(held, 'ping')+ assert result.get('status') == 'ambiguous' and 'Do not resend' in result['error'], result+ assert [path.name for path in held.dm_dir.glob('*.live.json')], 'an unproven refusal keeps its intent'+++async def test_a_refusal_alone_leaves_the_id_open_for_a_same_id_retry(held):+ """Only the Bot DM tool's settle records a not-sent disposition. A producer that retries its+ queued record under the same id (the cron drain) after a held refusal still admits it once."""+ from hermes_cli.gateway_client import GatewayRPCError+ delivery_id = 'c' * 64+ with pytest.raises(GatewayRPCError) as refused:+ await asyncio.to_thread(_resubmit, held, delivery_id, 'cron report')+ assert str(refused.value) == 'runtime_coordination_required' and refused.value.data.get('admitted') is False+ held.release()+ admitted = await asyncio.to_thread(_resubmit, held, delivery_id, 'cron report')+ assert admitted.get('admission_id') and _admissions(held) == ['bot:' + delivery_id], admitteddiff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.pyindex 3c104d66c29..850ff4196b0 100644--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@ -64,6 +64,16 @@ def find_canonical_live_owner(profile_home: Path | str) -> dict[str, Any] | Nonedef authority_delivery(home, params):"""Call only this home's already-running authority; never start a fallback."""+ return _authority_rpc(home, 'bot_relay.deliver', params)+++def authority_settle(home, params):+ """The same authority's ``bot_relay.settle``: the delivery id settled as never sent, or its+ existing receipt (``gateway/session_bot.py:_settle``)."""+ return _authority_rpc(home, 'bot_relay.settle', params)+++def _authority_rpc(home, method, params):import asynciofrom hermes_cli.gateway_runtime import discover_gateway_endpointfrom hermes_cli.gateway_client import GATEWAY_WS_PROTOCOL, GatewayClient, _session_ticket, gateway_ws_target@@ -83,7 +93,7 @@ def authority_delivery(home, params):if ws.subprotocol != GATEWAY_WS_PROTOCOL:raise ValueError('authority protocol mismatch')async with GatewayClient(ws) as client:- return await client.rpc('bot_relay.deliver', **params)+ return await client.rpc(method, **params)return asyncio.run(request())@@ -308,6 +318,19 @@ def deliver_to_live_owner(Retry with the same id AND pinned owner/message to inspect the existingstate. Reusing an id with a different payload is an error, never an overwrite."""+ return _door(authority_delivery, profile_home, owner, message, delivery_id=delivery_id, author=author,+ notification_category=notification_category)+++def settle_held_delivery(profile_home: Path | str, owner: dict[str, Any], message: str, *, delivery_id: str,+ author: dict[str, Any] | None = None) -> dict[str, Any]:+ """Finalize a refusal marked ``admitted: false`` under the same identity: the owner's terminal+ not-sent receipt (``refused``), or the receipt of an attempt that admitted the id meanwhile."""+ return _door(authority_settle, profile_home, owner, message, delivery_id=delivery_id, author=author)+++def _door(call: Callable[[Path, dict], dict], profile_home, owner, message, *, delivery_id=None, author=None,+ notification_category="result"):pinned = _owner(profile_home, owner)if not isinstance(message, str):raise ValueError("message must be a string")@@ -317,7 +340,7 @@ def deliver_to_live_owner(category = {"notification_category": "diagnostic"} if notification_category == "diagnostic" else {}# The authority refuses a category-changing replay (admission_conflict), so the admitted# category is the producer's; echo it so callers can check the receipt's identity.- return {**authority_delivery(home, dict(id=_delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex),+ return {**call(home, dict(id=_delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex),profile=home.name if home.parent.name == "profiles" else "default",message=message, **({"session_id": pinned["session_id"]} if pinned["session_id"] else {}),**({"author": dict(author)} if author else {}), **category)), **category}diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex df002ba91b0..24b8433dd18 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -438,11 +438,42 @@ class LiveTargetUnavailableError(RuntimeError):this is a definite no-send the sender may retry, not the ambiguous post-admission state."""reason = "runtime_unavailable"+ resend = "once the target is up"-def _unavailable_payload(dm_file: str, exc: BaseException) -> str:- return json.dumps({"reason": LiveTargetUnavailableError.reason, "delivery_id": _dm_delivery_id(dm_file),- "error": f"{exc} — the message was NOT sent; it is safe to resend once the target is up."})+class LiveTargetHeldError(LiveTargetUnavailableError):+ """The owner refused because another session writer holds the Bot Chat, and settled this+ delivery id as never sent (``bot_relay.settle``): every later attempt under the id gets that+ disposition, so this is a definite no-send too. A refusal without that settlement stays the+ ambiguous outcome."""++ reason = "runtime_coordination_required"+ resend = "after that session closes"+++def _unavailable_payload(dm_file: str, exc: LiveTargetUnavailableError) -> str:+ return json.dumps({"reason": exc.reason, "delivery_id": _dm_delivery_id(dm_file),+ "error": f"{exc} — the message was NOT sent; it is safe to resend {exc.resend}."})+++def _settled_no_send(dm_file: str, exc: LiveTargetUnavailableError) -> str:+ """The answer to a definite no-send, for both the tool and its runner: first the payload and+ any pinned intent go, so nothing local can rebuild or replay the delivery. A file that is still+ there is not settlement: the answer is then the unknown outcome, never "safe to resend"."""+ left = []+ for path in (_live_intent_file(dm_file), dm_file):+ _unlink_dm_file(path)+ if os.path.lexists(path):+ left.append(path)+ if left:+ return _live_outcome_unknown(dm_file, f"could not remove {left[0]}")+ return _unavailable_payload(dm_file, exc)+++def _held_disposition(record: dict | None) -> bool:+ """The owner's terminal not-sent receipt for a delivery refused while another writer held the+ chat (``gateway/session_bot.py:_not_sent_record``)."""+ return bool(record) and record.get("refused") is True and record.get("reason") == LiveTargetHeldError.reasondef _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dict] = None) -> dict | None:@@ -479,8 +510,21 @@ def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dichome = intent["owner"]["profile_home"]record = read_delivery_result(home, intent["delivery_id"])if record is None or intent["owner"].get("canonical"):- record = deliver_to_live_owner(home, intent["owner"], intent["message"],- delivery_id=intent["delivery_id"], author=intent.get("author"))+ from hermes_cli.gateway_client import GatewayRPCError+ from tools.bot_live_delivery import settle_held_delivery++ identity = dict(delivery_id=intent["delivery_id"], author=intent.get("author"))+ try:+ record = deliver_to_live_owner(home, intent["owner"], intent["message"], **identity)+ except GatewayRPCError as exc:+ if str(exc) != LiveTargetHeldError.reason or exc.data.get("admitted") is not False:+ raise+ # Nothing was admitted while that refusal held the owner's lock, but a same-id attempt+ # may have admitted since: only the owner's settle decides, under that same lock.+ record = settle_held_delivery(home, intent["owner"], intent["message"], **identity)+ if _held_disposition(record):+ # The callers remove the intent and payload (``_settled_no_send``).+ raise LiveTargetHeldError("Bot Chat is held by another session writer")return record@@ -577,6 +621,9 @@ def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool,if home is not None or os.path.exists(_live_intent_file(dm_file)):try:record = _admit_live_dm(home, dm_file, author)+ except LiveTargetHeldError as exc:+ print(_settled_no_send(dm_file, exc)) # the owner settled the id: drop the payload too+ return 1except LiveTargetUnavailableError as exc:print(_unavailable_payload(dm_file, exc))return 1@@ -630,9 +677,7 @@ def _start_delivery(argv: list[str], content: str, label: str, *, stdin_file: botry:record = _admit_live_dm(profile_home, dm_file, author)except LiveTargetUnavailableError as exc:- payload = _unavailable_payload(dm_file, exc)- _unlink_dm_file(dm_file) # no intent was pinned: nothing will ever replay this file- return payload+ return _settled_no_send(dm_file, exc)except Exception as exc:return json.dumps({"status": "ambiguous", "delivery_id": _dm_delivery_id(dm_file),"error": f"Live delivery admission could not be confirmed: {exc}. Do not resend.",diff --git a/tui_gateway/contracts/canonical_projections.py b/tui_gateway/contracts/canonical_projections.pyindex ef9e7bcfe5e..7b8931440e4 100644--- a/tui_gateway/contracts/canonical_projections.py+++ b/tui_gateway/contracts/canonical_projections.py@@ -107,5 +107,8 @@ for _name, _params, _result in (('groups.create', CanonicalRoomCreateParams, GroupsCreateResult),('groups.approve', CanonicalRoomApproveParams, GroupsApproveResult),('bot_relay.deliver', CanonicalBotDeliverParams, CanonicalBotDeliverResult),+ # The sender's finalize of a refusal marked ``admitted: false``: the same identity, answered+ # with the id's terminal not-sent receipt or its existing admission (``gateway/session_bot.py``).+ ('bot_relay.settle', CanonicalBotDeliverParams, CanonicalBotDeliverResult),):canonical_method(_name, params=_params, result=_result)