The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: explicit TUI attach negotiates the canonical wire when the endpoint has an authority
Teknium3187905d0776
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex f9e835817d9..25836cafb4c 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -5164,6 +5164,7 @@ export interface GatewayReadyPayload {change_events: booleanreplay_epoch: stringheartbeat?: boolean | null+ session_authority?: boolean | null}/** ``tui_gateway/change_watcher.py::resolve_skin`` — the resolved active skin (``HermesSkin``). ``{}`` when the skin engine failed to load. Colour maps are token → colour string. */export interface SkinPayload {diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex a0a7fde5b6c..97244adf0c6 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -17149,6 +17149,18 @@],"default": null,"title": "Heartbeat"+ },+ "session_authority": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Session Authority"}},"required": [diff --git a/tests/tui_gateway/test_tui_gateway_ws.py b/tests/tui_gateway/test_tui_gateway_ws.pyindex 850a59160e1..036aaa145aa 100644--- a/tests/tui_gateway/test_tui_gateway_ws.py+++ b/tests/tui_gateway/test_tui_gateway_ws.py@@ -409,7 +409,7 @@ _INTERACTIVE = frozenset({"session:create", "session:read", "session:submit", "sdef _drive_authority_fallback(monkeypatch, *, capabilities, profile_id, method):"""One RPC through handle_ws on an authority connection whose dispatch answers -32601, so therequest takes the legacy-fallback branch (R2-M3). Returns the reply frame for id 1."""- import gateway.session_controls as session_controls+ from gateway import session_controlsclass FakeConnection:def __init__(self, authority, transport, identity, operator=False):@@ -446,6 +446,44 @@ def _drive_authority_fallback(monkeypatch, *, capabilities, profile_id, method):return next(frame for frame in sent if frame.get("id") == 1)+def test_ready_frame_advertises_a_session_authority_only_when_one_is_bound(monkeypatch):+ """An explicit TUI attach (HERMES_TUI_GATEWAY_URL) negotiates the canonical wire from this flag."""+ from gateway import session_controls++ class FakeConnection:+ def __init__(self, authority, transport, identity, operator=False):+ self.actor = type("Actor", (), {"capabilities": frozenset(), "profile_id": "p"})()++ async def close(self):+ pass++ monkeypatch.setattr(session_controls, "AuthorityConnection", FakeConnection)+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)++ def ready(scope):+ sent = []++ class FakeWS:+ async def accept(self, **_kw):+ pass++ async def send_text(self, line):+ sent.extend(json.loads(part) for part in line.splitlines() if part.strip())++ async def receive_text(self):+ raise ws_mod._WebSocketDisconnect()++ async def close(self, **_kw):+ pass++ FakeWS.scope = scope+ asyncio.run(ws_mod.handle_ws(FakeWS(), auth_identity={"user_id": "u"}))+ return sent[0]["params"]["payload"]++ assert ready({"hermes.session_authority": object()})["session_authority"] is True+ assert "session_authority" not in ready({})++def test_legacy_fallback_requires_the_interactive_grant(monkeypatch):"""A worker-adoption ticket (or any connection without the authority's interactive grant) mustnot reach general legacy dispatch after an authority -32601; an interactive one still does."""diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex 812a556a30e..d7e79376cb4 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -55,6 +55,9 @@ class GatewayReadyPayload(Payload):change_events: boolreplay_epoch: strheartbeat: bool | None = None # WebSocket transport only+ # WebSocket transport bound to a session authority: session verbs speak the canonical wire+ # (``runtime.describe`` / ``session.create source=…``), so an explicit attach must negotiate it.+ session_authority: bool | None = Noneevent("gateway.ready", GatewayReadyPayload,diff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex a1856ac6ebb..c1b160ea0ae 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -416,6 +416,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:"jsonrpc": "2.0", "method": "event","params": {"type": "gateway.ready", "payload": {"skin": skin_payload, "change_events": True, "heartbeat": True, "replay_epoch": replay_epoch(),+ **({"session_authority": True} if authority_connection is not None else {}),}},})if ready_ok:diff --git a/ui-tui/src/__tests__/gatewayClient.test.ts b/ui-tui/src/__tests__/gatewayClient.test.tsindex ecc1388f746..d1ef6f76c68 100644--- a/ui-tui/src/__tests__/gatewayClient.test.ts+++ b/ui-tui/src/__tests__/gatewayClient.test.ts@@ -299,6 +299,40 @@ describe('GatewayClient websocket attach mode', () => {} finally { gw.kill(); vi.useRealTimers() }})+ it('negotiates the canonical wire on an explicit attach whose listener advertises a session authority', async () => {+ process.env.HERMES_TUI_GATEWAY_URL = 'ws://gateway.test/api/ws?token=abc'+ const gw = new GatewayClient()+ const events: any[] = []++ gw.on('event', event => events.push(event))+ gw.start()+ gw.drain()+ const socket = FakeWebSocket.instances[0]!+ const frames = () => socket.sent.map(text => JSON.parse(text) as { id: number; method: string; params: any })++ socket.open()+ socket.message(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready',+ payload: { skin: { name: 'mono' }, session_authority: true } } }))+ await vi.waitFor(() => expect(frames().some(frame => frame.method === 'runtime.describe')).toBe(true))+ expect(events.some(event => event.type === 'gateway.ready')).toBe(false)+ socket.message(JSON.stringify({ jsonrpc: '2.0', id: frames().find(f => f.method === 'runtime.describe')!.id,+ result: { session_create: { sources: ['tui'], parameters: ['source', 'request_id', 'model'] } } }))+ await vi.waitFor(() => expect(events.filter(event => event.type === 'gateway.ready')).toHaveLength(1))+ expect(events.find(event => event.type === 'gateway.ready').payload.skin).toEqual({ name: 'mono' })+ expect(gw.isCanonical).toBe(true)++ const created = gw.request<{ session_id: string }>('session.create', { cols: 80, model: 'm' })++ await vi.waitFor(() => expect(frames().some(frame => frame.method === 'session.create')).toBe(true))+ const create = frames().find(frame => frame.method === 'session.create')!++ expect(create.params).toMatchObject({ source: 'tui', model: 'm' })+ expect(create.params).not.toHaveProperty('cols')+ socket.message(JSON.stringify({ jsonrpc: '2.0', id: create.id, result: { session_id: 'fresh', info: {} } }))+ await expect(created).resolves.toMatchObject({ session_id: 'fresh' })+ gw.kill()+ })+it('waits for websocket open and resolves RPC requests', async () => {process.env.HERMES_TUI_GATEWAY_URL = 'ws://gateway.test/api/ws?token=abc'const gw = new GatewayClient()diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.tsindex cdbac9d8bda..dfb1a54205a 100644--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@ -211,6 +211,13 @@ export class GatewayClient extends EventEmitter {* `gateway.ready` itself after `runtime.describe`, so the listener's ready would be a* second one) while still negotiating the transport's heartbeat capability. */private publishWire(ev: AnyGatewayEvent) {+ if (!this.isCanonical && ev.type === 'gateway.ready' && this.attachUrl !== null &&+ (ev as { payload?: { session_authority?: boolean } }).payload?.session_authority === true) {+ // An explicit HERMES_TUI_GATEWAY_URL endpoint whose session verbs belong to an authority:+ // negotiate the canonical wire exactly like a local grant, keeping the listener's skin.+ return this.adoptCanonicalAttach(ev as GatewayEvent<'gateway.ready'>)+ }+if (this.isCanonical && ev.type === 'gateway.ready') {if ((ev as GatewayEvent<'gateway.ready'>).payload?.heartbeat && this.ws?.readyState === WS_OPEN) {this.channel.startHeartbeat()@@ -228,6 +235,27 @@ export class GatewayClient extends EventEmitter {this.publish(ev)}+ private adoptCanonicalAttach(ev: GatewayEvent<'gateway.ready'>) {+ const ws = this.ws++ this.isCanonical = true++ if (ev.payload?.heartbeat && ws?.readyState === WS_OPEN) {+ this.channel.startHeartbeat()+ }++ this.describeFlight = undefined+ void this.describeRuntime().then(() => {+ if (this.ws === ws) {+ this.publish({ type: 'gateway.ready', payload: { skin: ev.payload?.skin } } as unknown as AnyGatewayEvent)+ }+ }).catch(error => {+ this.publish({ type: 'gateway.start_timeout', payload: {+ python: 'runtime.describe', cwd: '', stderr_tail: String(error)+ } })+ })+ }+private publish(ev: AnyGatewayEvent) {if (ev.type === 'gateway.ready') {this.ready = true@@ -687,6 +715,9 @@ export class GatewayClient extends EventEmitter {this.closeSidecarSocket()if (attachUrl) {+ // Each explicit connection negotiates its wire from the listener's ready frame.+ this.isCanonical = false+ this.creationContract = undefinedthis.startAttachedGateway(attachUrl)return@@ -830,14 +861,23 @@ export class GatewayClient extends EventEmitter {this.start()}- return this.requestOverWebSocket<T>(method, params, timeoutMs)+ return this.isCanonical+ ? this.requestCanonical<T>(method, params, timeoutMs)+ : this.requestOverWebSocket<T>(method, params, timeoutMs)}if (!this.bootstrapFlight) { this.start() }- return this.bootstrapFlight!.then(async () => {+ return this.bootstrapFlight!.then(() => {if (this.bootstrapError) { throw this.bootstrapError }+ return this.requestCanonical<T>(method, params, timeoutMs)+ })+ }++ /** One request through the canonical wire adapter (local grant or negotiated explicit attach). */+ private requestCanonical<T>(method: string, params: Record<string, unknown>, timeoutMs?: number): Promise<T> {+ return (async () => {if (method === 'session.create' && !this.creationContract) { await this.describeRuntime() }const request = canonicalRequest(method, params, this.creationContract)const toolProgress = method === 'session.create' ? launchToolProgress() : undefined@@ -851,7 +891,7 @@ export class GatewayClient extends EventEmitter {}return canonicalResult(method, value, request.params)- })+ })()}kill(reason = 'requested') {