The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): declare a refused Bot delivery's receipt in the deliver contract
unsupportedpastelsfe0588bedca9
diff --git a/apps/desktop/src/plugins/hermes-bots/relay.test.ts b/apps/desktop/src/plugins/hermes-bots/relay.test.tsindex 5e5053b8aec..8be00078d66 100644--- a/apps/desktop/src/plugins/hermes-bots/relay.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.test.ts@@ -942,6 +942,45 @@ describe('the drain loop wires drain → deliver → reply', () => {stopBotRelay()})+ it('posts a refused receipt back as the sender’s terminal answer, without an admission', async () => {+ // A same-id resend after the FIFO refused the delivery (nothing committed) answers the+ // declared refused result: terminal, so the refusal reaches the sender instead of staying retained.+ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {return { envelopes: call.connectionId === 'a' ? [envelope] : [] }}++ if (call.method === 'bot_relay.deliver') {+ return { status: 'failed', refused: true, delivery_id: envelope.id, error: 'Bot Chat delivery refused',+ reason: 'agent_blocked', reply: '' }+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()+ startBotRelay()+ await pushAndSettle()+ expect(calls.find(call => call.method === 'bot_relay.reply')?.params).toEqual({+ id: envelope.id, error: 'Bot Chat delivery refused', reason: 'agent_blocked'+ })+ stopBotRelay()+ })++ it('retains an answer with neither an admission nor a refusal', async () => {+ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {return { envelopes: call.connectionId === 'a' ? [envelope] : [] }}++ if (call.method === 'bot_relay.deliver') {return { status: 'failed', delivery_id: envelope.id, error: 'lost' }}++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()+ startBotRelay()+ await pushAndSettle()+ expect(calls.filter(call => call.method === 'bot_relay.reply')).toHaveLength(0)+ stopBotRelay()+ })+it('tells the target which connection the sender is on, so its author id names the machine', async () => {const calls = respondWith(call => {if (call.method === 'bot_relay.outbox.drain') {diff --git a/apps/desktop/src/plugins/hermes-bots/relay.ts b/apps/desktop/src/plugins/hermes-bots/relay.tsindex ff2cb96b081..40bd20a167e 100644--- a/apps/desktop/src/plugins/hermes-bots/relay.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts@@ -659,15 +659,28 @@ function relayDeliverParams(sender: RelayConnection, envelope: RelayEnvelope, en}}+type RelayDeliverResult = {+ status?: string+ delivery_id?: string+ admission_id?: string | null+ refused?: true | null+ reply?: string+ error?: string+ reason?: string+}+/** Act on a `bot_relay.deliver` answer: only a settled/failed receipt for THIS- * envelope posts back; anything else stays retained for recovery. */+ * envelope posts back; anything else stays retained for recovery. A receipt+ * names its admission, or is `refused` (terminal `failed`, nothing admitted). */async function settleRelayDelivery(- res: { status?: string; delivery_id?: string; admission_id?: string; reply?: string; error?: string; reason?: string },+ res: RelayDeliverResult,envelopeId: string,attentionKey: string,postReply: (payload: { error?: string; reason?: string; reply?: string }) => Promise<void>) {- if (res.delivery_id !== envelopeId || !res.admission_id) {+ const refused = res.refused === true && res.status === 'failed'++ if (res.delivery_id !== envelopeId || !(res.admission_id || refused)) {noteBotAttention(attentionKey, 'Delivery identity unavailable; retained for recovery')return@@ -734,7 +747,7 @@ async function deliverRelayEnvelope(const attentionKey = `${target.id}::${String(envelope?.target_profile || '')}`try {- const res = await host.requestProfile<{ status?: string; delivery_id?: string; admission_id?: string; reply?: string; error?: string; reason?: string }>(+ const res = await host.requestProfile<RelayDeliverResult>({ ...target.route, profile: String(envelope.target_profile), targetProfile: String(envelope.target_profile) },'bot_relay.deliver',relayDeliverParams(sender, envelope, envelopeId),diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 3aa7ac2bbd5..6cf4a26fa5f 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -5186,12 +5186,14 @@ export interface CanonicalBotDeliverParams {author?: Record<string, unknown> | nullnotification_category?: string | null}+/** A delivery's receipt. It names its admission, unless ``refused``: the FIFO refused the delivery before anything was committed (``gateway/session_bot.py``), a terminal ``failed`` receipt with no admission that the relay settles as the sender's answer. */export interface CanonicalBotDeliverResult {status: stringdelivery_id: stringprofile_home: stringsession_id: string- admission_id: string+ admission_id?: string | null+ refused?: true | nullmessage: stringreply?: string | nullretry_admission_id?: string | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex f6f1a35fe83..55ea261ddd0 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -8084,6 +8084,7 @@},"CanonicalBotDeliverResult": {"additionalProperties": false,+ "description": "A delivery's receipt. It names its admission, unless ``refused``: the FIFO refused the\ndelivery before anything was committed (``gateway/session_bot.py``), a terminal ``failed``\nreceipt with no admission that the relay settles as the sender's answer.","properties": {"status": {"title": "Status",@@ -8102,8 +8103,29 @@"type": "string"},"admission_id": {- "title": "Admission Id",- "type": "string"+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Admission Id"+ },+ "refused": {+ "anyOf": [+ {+ "const": true,+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Refused"},"message": {"title": "Message",@@ -8163,7 +8185,6 @@"delivery_id","profile_home","session_id",- "admission_id","message"],"title": "CanonicalBotDeliverResult",diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 1c5baf17b1d..480cb8f33fe 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -528,8 +528,8 @@ async def _deliver(connection, params):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 {k: record[k] for k in ('status', 'delivery_id', 'profile_home', 'session_id', 'message',- 'reply', 'error', 'reason')}+ return {k: record[k] for k in ('status', 'refused', 'delivery_id', 'profile_home', 'session_id',+ 'message', 'reply', 'error', 'reason')}if record is not None:raise RuntimeStoreError('unknown_execution')ref, live, entry = await _target(authority, actor)diff --git a/tests/gateway/test_bot_receipt_refusal.py b/tests/gateway/test_bot_receipt_refusal.pyindex 6d8558eea69..90aeef0deb7 100644--- a/tests/gateway/test_bot_receipt_refusal.py+++ b/tests/gateway/test_bot_receipt_refusal.py@@ -52,6 +52,35 @@ async def test_refused_delivery_leaves_a_terminal_receipt_the_scan_accepts(bot,assert list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False) == []+def _rpc_connection(bot):+ """The relay Desktop's own connection: ``bot_relay.deliver`` crosses the contract-checked dispatch."""+ from gateway.session_controls import AuthorityConnection+ return AuthorityConnection(bot.authority, object(), {+ 'user_id': 'uid:1000', 'provider': 'local', 'profile_id': bot.authority.profile_id,+ 'instance_id': bot.authority.instance_id,+ 'capabilities': ['session:read', 'session:submit', 'session:control', 'session:create']})+++async def test_a_refused_delivery_answers_through_the_deliver_contract(bot, monkeypatch):+ """The first refusal is a JSON-RPC refusal; the same-id resend is the declared refused result+ (terminal ``failed``, ``refused``, no admission), never a ``ContractViolation``."""+ connection = _rpc_connection(bot)+ # The fixture's profile_id is no home path: route ``profile`` to this authority, as for a real home.+ monkeypatch.setattr(connection, '_sibling_for', lambda profile: None)+ request = {'id': 1, 'method': 'bot_relay.deliver', 'params': dict(id=KEY, profile='default', message='ping')}+ refusing = _refuse(monkeypatch, 'permission_denied')+ first = await connection.dispatch(request)+ assert first['error']['data']['reason'] == 'permission_denied', first+ refusing.clear()+ again = await connection.dispatch(request)+ assert 'result' in again, again+ result = again['result']+ assert (result['status'], result['refused'], result['reason']) == ('failed', True, 'agent_blocked'), result+ assert result['delivery_id'] == KEY and 'admission_id' not in result+ assert list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False) == []++AUTHOR = {'id': 'bot:cto', 'name': 'cto', 'is_bot': True}diff --git a/tui_gateway/contracts/canonical_projections.py b/tui_gateway/contracts/canonical_projections.pyindex 52f6f2395d9..ef9e7bcfe5e 100644--- a/tui_gateway/contracts/canonical_projections.py+++ b/tui_gateway/contracts/canonical_projections.py@@ -1,6 +1,8 @@"""Canonical projections with demonstrated differences from standalone wire."""from typing import Literal+from pydantic import model_validator+from .base import JsonValue, Params, Resultfrom .common import ProfileParamsfrom .canonical_sessions import CanonicalSessionParams@@ -73,17 +75,28 @@ class CanonicalBotDeliverParams(Params):class CanonicalBotDeliverResult(Result):+ """A delivery's receipt. It names its admission, unless ``refused``: the FIFO refused the+ delivery before anything was committed (``gateway/session_bot.py``), a terminal ``failed``+ receipt with no admission that the relay settles as the sender's answer."""+status: strdelivery_id: strprofile_home: strsession_id: str- admission_id: str+ admission_id: str | None = None+ refused: Literal[True] | None = Nonemessage: strreply: str | None = Noneretry_admission_id: str | None = Noneerror: str | None = Nonereason: str | None = None+ @model_validator(mode='after')+ def _admitted_or_refused(self):+ if (self.admission_id is None) != (self.refused is True) or (self.refused and self.status != 'failed'):+ raise ValueError('a deliver result names its admission, or is a refused failed receipt without one')+ return self+for _name, _params, _result in (('config.get', ConfigGetParams, CanonicalConfigGetResult),