Skip to content

The agent that grows with you

feat: bind Ink sessions and controls to canonical authority envelopes

Tekniuma2d9e258daa9
diff --git a/ui-tui/CANONICAL_GATEWAY.md b/ui-tui/CANONICAL_GATEWAY.md
new file mode 100644
index 00000000000..0175b89a3e6
--- /dev/null
+++ b/ui-tui/CANONICAL_GATEWAY.md
@@ -0,0 +1,52 @@
+# Ink canonical local gateway connection
+
+Normal local Ink startup now ensures the profile's ordinary gateway through
+`ensure_gateway_runtime`, obtains an instance/profile-bound private control ticket,
+and connects over authenticated WebSocket. The short Python bootstrap subprocess
+is only a client; Ink no longer starts `tui_gateway.entry` or owns an agent loop.
+The ticket travels through a private child pipe and WebSocket subprotocol, never
+in an endpoint URL or discovery receipt. Explicit remote URLs remain remote: a
+failed connection cannot fall back to a local daemon.
+
+Closing Ink detaches its socket without stopping the gateway. Reconnection gets
+a fresh single-use ticket using discovery only; it cannot resurrect an explicitly
+stopped gateway. An initial ensure failure is visible and does not create a rival
+owner. Local profile selection remains the launcher's exact effective HERMES_HOME.
+
+Ink requires `runtime.describe.session_create` to advertise the `tui` source and
+every requested creation parameter. It sends a fresh `request_id`, `source: tui`,
+and explicit launcher options; an older CLI-only runtime returns a visible policy
+compatibility failure rather than silently creating CLI-policy work. Attach to an
+existing session does not apply the viewer's creation options.
+
+Prepared submission IDs and captured destination fences remain authoritative.
+The wire adapter maps `submission_id` to canonical `input_id` and translates the
+receipt's `ref` into the existing journal acknowledgement shape. Resume/create
+snapshots and events retain the authority epoch and execution generation. Shared
+approval/clarify responses carry the actual prompt ID and generation; a resumed
+snapshot restores its pending prompt cards. Stop includes the active generation.
+
+## Current gaps
+
+- The baseline runtime supports only CLI creation; fresh TUI creation needs the
+ separately integrated TUI launch-policy support. No CLI impersonation is used.
+- Runtime descriptions and session metadata are intentionally narrow. Ink renders
+ an explicit unavailable-inventory message, not fabricated tool/skill lists.
+- Most legacy rich UI RPCs (config, wake, slash execution, uploads, historical
+ pickers, metadata editing, and subagents) are not exposed by this authority yet;
+ they fail visibly. This is not complete feature parity.
+- A per-view session switch does not terminate the old shared session. The present
+ authority removes subscriptions when the socket closes, so old subscriptions
+ can remain until that detach; the renderer still filters by current session.
+- Secret/sudo and batch clarification are not claimed supported. Cold owner
+ restart recovery is outside this scoped migration.
+
+## Native verification
+
+`python ui-tui/scripts/native_canonical_probe.py <receipt-directory>` uses a
+private temporary HOME/HERMES_HOME, an ordinary no-platform daemon, a loopback
+OpenAI-compatible model, and real Ink processes on native Linux PTYs. It creates
+an explicitly labelled seed session with the runtime's supported policy, resumes
+it from two Ink viewers, submits through the real renderer, checks both rendered
+replies, detaches both viewers, and resumes persisted history in a new Ink process.
+The fixture does not replace renderer predicates or inject RPC results.
diff --git a/ui-tui/scripts/native_canonical_probe.py b/ui-tui/scripts/native_canonical_probe.py
new file mode 100644
index 00000000000..90667d09d86
--- /dev/null
+++ b/ui-tui/scripts/native_canonical_probe.py
@@ -0,0 +1,168 @@
+"""Disposable ordinary-daemon + real Ink PTY probe (no renderer injection)."""
+import asyncio
+import fcntl
+import importlib.util
+import json
+import os
+from pathlib import Path
+import pty
+import select
+import signal
+import socket
+import struct
+import subprocess
+import sys
+import tempfile
+import termios
+import threading
+import time
+from http.server import ThreadingHTTPServer
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+from tests.gateway.fixtures.shared_authority_peer import ModelPeer
+from websockets.asyncio.client import connect
+
+
+def run():
+ receipts = {}
+ with tempfile.TemporaryDirectory(prefix='ink-native-authority-') as temp:
+ base = Path(temp)
+ home = base / 'state'
+ home.mkdir(mode=0o700)
+ user = base / 'user'
+ user.mkdir()
+ model = ThreadingHTTPServer(('127.0.0.1', 0), ModelPeer)
+ model.requests, model.metadata_requests = [], []
+ threading.Thread(target=model.serve_forever, daemon=True).start()
+ model_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-wire-stub', 'base_url': model_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), PYTHONUNBUFFERED='1', HERMES_PYTHON=sys.executable,
+ HERMES_PYTHON_SRC_ROOT=str(ROOT), TERM='xterm-256color',
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=model_url)
+ children = []
+ daemon = None
+
+ def grant():
+ result = subprocess.run([sys.executable, str(ROOT / 'ui-tui/scripts/gateway_bootstrap.py')],
+ cwd=ROOT, env=env, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, timeout=10)
+ assert result.returncode == 0, result.stderr
+ return json.loads(result.stdout)
+
+ async def rpc(ws, method, **params):
+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': method, 'method': method, 'params': params}))
+ async with asyncio.timeout(15):
+ while True:
+ reply = json.loads(await ws.recv())
+ if reply.get('id') == method:
+ assert 'result' in reply, reply
+ return reply['result']
+
+ async def seed():
+ g = grant()
+ async with connect(g['url'], subprotocols=g['protocols']) as ws:
+ description = await rpc(ws, 'runtime.describe')
+ source = 'tui' if 'tui' in description['session_create']['sources'] else 'cli'
+ result = await rpc(ws, 'session.create', request_id='native-seed', source=source)
+ receipts['seed_source'] = source
+ receipts['session_id'] = result['session_id']
+ return result['session_id']
+
+ def launch(name, sid=None, query=None):
+ master, slave = pty.openpty()
+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 36, 120, 0, 0))
+ launch_env = dict(env)
+ launch_env['HERMES_TUI_ACTIVE_SESSION_FILE'] = str(base / (name + '.json'))
+ if sid:
+ launch_env['HERMES_TUI_RESUME'] = sid
+ if query:
+ launch_env['HERMES_TUI_QUERY'] = query
+ proc = subprocess.Popen(['node', str(ROOT / 'ui-tui/dist/entry.js')], cwd=ROOT,
+ env=launch_env, stdin=slave, stdout=slave, stderr=slave,
+ start_new_session=True)
+ os.close(slave)
+ children.append((proc, master))
+ output = bytearray()
+ def drain():
+ while proc.poll() is None:
+ if select.select([master], [], [], .1)[0]:
+ try:
+ output.extend(os.read(master, 65536))
+ except OSError:
+ break
+ threading.Thread(target=drain, daemon=True).start()
+ return proc, master, output
+
+ try:
+ log = (base / 'daemon.log').open('w+')
+ daemon = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=ROOT, env=env,
+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
+ deadline = time.monotonic() + 35
+ while time.monotonic() < deadline:
+ try:
+ g = grant()
+ break
+ except AssertionError:
+ assert daemon.poll() is None, 'daemon exited'
+ time.sleep(.1)
+ else:
+ raise AssertionError('daemon bootstrap readiness timeout')
+ receipts['instance_id'] = g['instance_id']
+ sid = asyncio.run(seed())
+ first = launch('first', sid, 'WS_SHARED')
+ second = launch('second', sid)
+ deadline = time.monotonic() + 35
+ while time.monotonic() < deadline and (not model.requests or b'LOCAL_ACK' not in first[2]):
+ assert first[0].poll() is None, bytes(first[2]).decode(errors='replace')
+ time.sleep(.1)
+ receipts['model_requests'] = len(model.requests)
+ receipts['first_rendered_reply'] = b'LOCAL_ACK' in first[2]
+ receipts['second_rendered_reply'] = b'LOCAL_ACK' in second[2]
+ for name, child in [('first', first), ('second', second)]:
+ (Path(sys.argv[1]) / (name + '.pty')).write_bytes(child[2])
+ assert receipts['first_rendered_reply'], bytes(first[2]).decode(errors='replace')[-12000:]
+ assert receipts['second_rendered_reply'], bytes(second[2]).decode(errors='replace')[-12000:]
+ first[0].terminate()
+ second[0].terminate()
+ first[0].wait(timeout=5)
+ second[0].wait(timeout=5)
+ third = launch('reconnected', sid)
+ deadline = time.monotonic() + 20
+ while time.monotonic() < deadline and b'LOCAL_ACK' not in third[2]:
+ time.sleep(.1)
+ receipts['reconnect_rendered_reply'] = b'LOCAL_ACK' in third[2]
+ receipts['daemon_survived_detach'] = daemon.poll() is None
+ assert receipts['reconnect_rendered_reply']
+ finally:
+ for proc, master in children:
+ if proc.poll() is None:
+ proc.terminate()
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait(timeout=5)
+ os.close(master)
+ if daemon and daemon.poll() is None:
+ daemon.send_signal(signal.SIGINT)
+ try:
+ daemon.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ daemon.kill()
+ daemon.wait(timeout=5)
+ model.shutdown()
+ model.server_close()
+ (Path(sys.argv[1]) / 'receipt.json').write_text(json.dumps(receipts, indent=2))
+ print(json.dumps(receipts), flush=True)
+
+
+if __name__ == '__main__':
+ Path(sys.argv[1]).mkdir(parents=True, exist_ok=True)
+ run()
diff --git a/ui-tui/src/__tests__/canonicalGateway.test.ts b/ui-tui/src/__tests__/canonicalGateway.test.ts
new file mode 100644
index 00000000000..c23cbcc9348
--- /dev/null
+++ b/ui-tui/src/__tests__/canonicalGateway.test.ts
@@ -0,0 +1,13 @@
+import { expect, it } from 'vitest'
+import { canonicalRequest, canonicalResult, sharedControlParams } from '../canonicalGateway.js'
+
+it('retains prepared identity and rejects unsupported TUI launch policy instead of impersonating CLI', () => {
+ const contract = { sources: ['tui'], parameters: ['request_id', 'source', 'model', 'cwd', 'toolsets'] }
+ expect(canonicalRequest('session.create', { request_id: 'fresh', model: 'local-model', cwd: '/tmp/project' }, contract)).toEqual({ method: 'session.create', params: { request_id: 'fresh', source: 'tui', model: 'local-model', cwd: '/tmp/project' } })
+ expect(() => canonicalRequest('session.create', {}, { sources: ['cli'], parameters: [] })).toThrow('tui')
+ expect(() => canonicalRequest('session.create', { skills: ['test'] }, contract)).toThrow('skills')
+ expect(canonicalRequest('prompt.submit', { session_id: 'sid', submission_id: 'prepared-id', text: 'hello', queued: true }, contract).params).toEqual({ session_id: 'sid', input_id: 'prepared-id', text: 'hello', queued: true })
+ expect(sharedControlParams({ sharedControl: { session_id: 'sid', execution_generation: 9, prompt_id: 'approval-9' } })).toEqual({ session_id: 'sid', execution_generation: 9, prompt_id: 'approval-9' })
+ const receipt = canonicalResult('prompt.submit', { admission_id: 'prepared-id', ref: { profile_id: '/tmp/profile', session_id: 'sid' }, status: 'queued' })
+ expect(receipt).toMatchObject({ admission_id: 'prepared-id', target_profile_home: '/tmp/profile', target_session_id: 'sid' })
+})
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index 505dd0d9335..e5f444a03be 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -795,6 +795,14 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
}
}
+ const settled = ev as unknown as { type: string; payload?: { prompt_id?: string } }
+ if (settled.type === 'approval.settled' || settled.type === 'clarify.settled') {
+ const kind = settled.type === 'approval.settled' ? 'approval' : 'clarify'
+ patchOverlayState(previous => previous[kind]?.sharedControl?.prompt_id === settled.payload?.prompt_id
+ ? { ...previous, [kind]: null } : previous)
+ return
+ }
+
switch (ev.type) {
case 'gateway.ready':
handleReady(ev.payload?.skin)
@@ -1292,6 +1300,9 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
}
case 'clarify.request': {
+ const shared = ev.payload as typeof ev.payload & { prompt_id?: string; execution_generation?: number }
+ const sharedControl = shared.prompt_id && ev.session_id && typeof shared.execution_generation === 'number'
+ ? { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id } : undefined
const batch = (ev.payload.questions ?? [])
.filter(q => typeof q?.qid === 'string' && q.qid && typeof q?.question === 'string' && q.question.trim())
.map(q => ({
@@ -1308,12 +1319,12 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
choices: null,
question: '',
questions: batch,
- requestId: ev.payload.request_id
+ requestId: shared.prompt_id ?? ev.payload.request_id, sharedControl
}
: {
choices: ev.payload.choices ?? null,
question: ev.payload.question ?? '',
- requestId: ev.payload.request_id
+ requestId: shared.prompt_id ?? ev.payload.request_id, sharedControl
}
})
setStatus('waiting for input…')
@@ -1323,6 +1334,9 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
}
case 'approval.request': {
+ const shared = ev.payload as typeof ev.payload & { prompt_id?: string; execution_generation?: number }
+ const sharedControl = shared.prompt_id && ev.session_id && typeof shared.execution_generation === 'number'
+ ? { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id } : undefined
const description = String(ev.payload.description ?? 'dangerous command')
// Only an explicit false (tirith warning) drops the permanent-allow option.
const allowPermanent = ev.payload.allow_permanent !== false
@@ -1330,6 +1344,7 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
patchOverlayState({
approval: {
allowPermanent,
+ sharedControl,
choices: ev.payload.choices,
command: String(ev.payload.command ?? ''),
description,
diff --git a/ui-tui/src/app/turnController.ts b/ui-tui/src/app/turnController.ts
index f6a1c53ef38..9b6e8a6a82e 100644
--- a/ui-tui/src/app/turnController.ts
+++ b/ui-tui/src/app/turnController.ts
@@ -98,7 +98,7 @@ const finalTail = (finalText: string, segments: Msg[]) => {
export interface InterruptDeps {
appendMessage: (msg: Msg) => void
- gw: { request: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T> }
+ gw: { isCanonical?: boolean; request: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T> }
sid: string
sys: (text: string) => void
}
@@ -308,7 +308,7 @@ class TurnController {
// cancelled turn's "[interrupted]" reply.
interruptTurn({ appendMessage, gw, sid, sys }: InterruptDeps, opts: { keepBusy?: boolean } = {}) {
this.interrupted = true
- gw.request<SessionInterruptResponse>('session.interrupt', { session_id: sid }).catch(() => {})
+ gw.request<SessionInterruptResponse>('session.interrupt', { session_id: sid, ...(gw.isCanonical ? { execution_generation: getUiState().info?.execution_generation } : {}) }).catch(() => {})
this.closeReasoningSegment()
diff --git a/ui-tui/src/app/useInputHandlers.ts b/ui-tui/src/app/useInputHandlers.ts
index 7eee3566218..f9857f6f560 100644
--- a/ui-tui/src/app/useInputHandlers.ts
+++ b/ui-tui/src/app/useInputHandlers.ts
@@ -1,3 +1,4 @@
+import { sharedControlParams } from '../canonicalGateway.js'
import { forceRedraw, useInput } from '@hermes/ink'
import { useStore } from '@nanostores/react'
import { useEffect, useRef } from 'react'
@@ -224,7 +225,7 @@ export function useInputHandlers(ctx: InputHandlerContext): InputHandlerResult {
return
}
return gateway
- .rpc<ApprovalRespondResponse>('approval.respond', { choice: 'deny', session_id: getUiState().sid })
+ .rpc<ApprovalRespondResponse>('approval.respond', { choice: 'deny', session_id: getUiState().sid, ...sharedControlParams(overlay.approval) })
.then(r => r && fresh() && (patchOverlayState({ approval: null }), patchTurnState({ outcome: 'denied' })))
}
diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.ts
index f9991a95d51..1caaf198132 100644
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@ -11,6 +11,7 @@ import {
import { useStore } from '@nanostores/react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { sharedControlParams } from '../canonicalGateway.js'
import { DASHBOARD_TUI_MODE, STARTUP_RESUME_ID } from '../config/env.js'
import { WHEEL_SCROLL_STEP } from '../config/limits.js'
import { RESIZE_COALESCE_MS } from '../config/timing.js'
@@ -713,7 +714,7 @@ export function useMainApp(gw: GatewayClient) {
turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
patchTurnState({ turnTrail: turnController.turnTools })
- rpc<ClarifyRespondResponse>('clarify.respond', { answer, request_id: clarify.requestId }).then(r => {
+ rpc<ClarifyRespondResponse>('clarify.respond', { answer, ...(clarify.sharedControl ? sharedControlParams(clarify) : { request_id: clarify.requestId }) }).then(r => {
if (!r || !fresh()) {
return
}
@@ -1034,7 +1035,7 @@ export function useMainApp(gw: GatewayClient) {
if (!fresh()) {
return
}
- return respondWith('approval.respond', { choice, session_id: ui.sid }, () => {
+ return respondWith('approval.respond', { choice, session_id: ui.sid, ...sharedControlParams(overlay.approval) }, () => {
if (!fresh()) {
return
}
diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.ts
index dc1ae14ca7d..b7912df4830 100644
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@ -1,3 +1,5 @@
+import { randomUUID } from 'node:crypto'
+import { localCreationOptions } from '../canonicalGateway.js'
import { writeFileSync } from 'node:fs'
import type { ScrollBoxHandle } from '@hermes/ink'
@@ -138,7 +140,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const closeSession = useCallback(
(targetSid?: null | string) =>
- targetSid ? rpc<SessionCloseResponse>('session.close', { session_id: targetSid }) : Promise.resolve(null),
+ targetSid && !gw.isCanonical ? rpc<SessionCloseResponse>('session.close', { session_id: targetSid }) : Promise.resolve(null),
[rpc]
)
@@ -191,7 +193,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
async (msg?: string, title?: string, keepCurrent = false) => {
const flight = ++attachmentFlight.current
const previousSid = getUiState().sid
- const setup = await rpc<SetupStatusResponse>('setup.status', {})
+ const setup = gw.isCanonical ? null : await rpc<SetupStatusResponse>('setup.status', {})
if (flight !== attachmentFlight.current) {return null}
@@ -208,7 +210,8 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
if (flight !== attachmentFlight.current) {return null}
}
- const r = await rpc<SessionCreateResponse>('session.create', { cols: colsRef.current })
+ const r = await rpc<SessionCreateResponse>('session.create', gw.isCanonical
+ ? { request_id: randomUUID(), ...localCreationOptions() } : { cols: colsRef.current })
if (flight !== attachmentFlight.current) {return null}
@@ -228,7 +231,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
patchUiState({
info,
sid: r.session_id,
- status: info?.version ? 'ready' : 'starting agent…',
+ status: gw.isCanonical || info?.version ? 'ready' : 'starting agent…',
usage: usageFrom(info)
})
@@ -353,7 +356,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
patchOverlayState({ sessions: false })
patchUiState({ status: 'resuming…' })
- rpc<SetupStatusResponse>('setup.status', {}).then(setup => {
+ ;(gw.isCanonical ? Promise.resolve(null) : rpc<SetupStatusResponse>('setup.status', {})).then(setup => {
if (flight !== attachmentFlight.current) {return}
if (setup?.provider_configured === false) {
@@ -396,6 +399,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
status: statusFromLiveSession(r.status, running),
usage: usageFrom(info)
})
+ gw.hydrateSharedPrompts?.(r)
hydrateLiveSessionInflight(r.inflight)
cancelResumeScrollRef.current?.()
cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)
diff --git a/ui-tui/src/canonicalGateway.ts b/ui-tui/src/canonicalGateway.ts
new file mode 100644
index 00000000000..6b6d2365a43
--- /dev/null
+++ b/ui-tui/src/canonicalGateway.ts
@@ -0,0 +1,52 @@
+import { randomUUID } from 'node:crypto'
+
+export interface SharedControl { session_id: string; execution_generation: number; prompt_id: string }
+export const sharedControlParams = (prompt?: { sharedControl?: SharedControl } | null) => prompt?.sharedControl ?? {}
+
+export interface CreationContract { sources: string[]; parameters: string[] }
+
+export function canonicalRequest(method: string, original: Record<string, unknown>, contract?: CreationContract) {
+ const params = { ...original }
+ if (method === 'session.create') {
+ delete params.cols
+ params.source = 'tui'
+ params.request_id ??= randomUUID()
+ if (!contract?.sources.includes('tui')) { throw new Error('gateway does not support tui session policy; update/restart the gateway') }
+ const unsupported = Object.keys(params).filter(key => !contract.parameters.includes(key))
+ if (unsupported.length) { throw new Error(`gateway does not support TUI launch options: ${unsupported.join(', ')}`) }
+ }
+ if (method === 'prompt.submit' && params.submission_id) {
+ params.input_id = params.submission_id
+ delete params.submission_id
+ }
+ if (method === 'session.resume' || method === 'session.activate') {
+ method = 'session.resume'
+ delete params.cols
+ delete params.omit_messages
+ }
+ return { method, params }
+}
+
+export function canonicalResult(method: string, value: any): any {
+ if (!value || typeof value !== 'object') { return value }
+ if (method === 'prompt.submit' && value.ref) {
+ return { ...value, target_profile_home: value.ref.profile_id, target_session_id: value.ref.session_id }
+ }
+ if (['session.create', 'session.resume', 'session.activate'].includes(method)) {
+ return { ...value, info: { ...value.info, stored_session_id: value.stored_session_id,
+ execution_epoch: String(value.authority_epoch), execution_generation: value.execution_generation,
+ running: value.running } }
+ }
+ return value
+}
+
+export function localCreationOptions(env = process.env): Record<string, unknown> {
+ const fields: Record<string, string | undefined> = {
+ model: env.HERMES_MODEL, provider: env.HERMES_TUI_PROVIDER, cwd: env.HERMES_CWD,
+ skills: env.HERMES_TUI_SKILLS, checkpoints: env.HERMES_TUI_CHECKPOINTS,
+ max_turns: env.HERMES_TUI_MAX_TURNS, accept_hooks: env.HERMES_ACCEPT_HOOKS
+ }
+ const options: Record<string, unknown> = Object.fromEntries(Object.entries(fields).filter(([, value]) => value))
+ if (env.HERMES_TUI_TOOLSETS) { options.toolsets = env.HERMES_TUI_TOOLSETS.split(',') }
+ return options
+}
diff --git a/ui-tui/src/components/branding.tsx b/ui-tui/src/components/branding.tsx
index 18fdf3332c7..20a43e65f53 100644
--- a/ui-tui/src/components/branding.tsx
+++ b/ui-tui/src/components/branding.tsx
@@ -249,6 +249,13 @@ export function SessionPanel({ info, maxWidth, sid, t }: SessionPanelProps) {
return line
}
+ // The canonical authority intentionally returns a narrow metadata snapshot.
+ // Do not invent tool/skill inventories or crash while rendering that session.
+ if (!info.skills || !info.tools) {
+ return <Box flexDirection="column"><Text color={t.color.muted}>Gateway session {sid}</Text>
+ <Text color={t.color.muted}>Tool and skill inventory is not exposed by this runtime.</Text></Box>
+ }
+
// ── Collapsible skills section ──
const skillEntries = Object.entries(info.skills).sort()
const skillsTotal = flat(info.skills).length
diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.ts
index b0c560a4ba5..8816ab36e53 100644
--- a/ui-tui/src/gatewayClient.ts
+++ b/ui-tui/src/gatewayClient.ts
@@ -6,6 +6,8 @@ import { promisify } from 'node:util'
import { WebSocket as UndiciWebSocket } from 'undici'
+import { canonicalRequest, canonicalResult, type CreationContract } from './canonicalGateway.js'
+
import type { GatewayEvent } from './gatewayTypes.js'
import { CircularBuffer } from './lib/circularBuffer.js'
import { recordParentLifecycle } from './lib/parentLog.js'
@@ -175,6 +177,7 @@ export class GatewayClient extends EventEmitter {
private localStarted = false
private localGeneration = 0
isCanonical = false
+ private creationContract?: CreationContract
constructor(private bootstrap: (start: boolean) => Promise<LocalGatewayGrant> = bootstrapLocalGateway) {
super()
@@ -443,6 +446,15 @@ export class GatewayClient extends EventEmitter {
}
}
+ hydrateSharedPrompts(snapshot: unknown) {
+ if (!this.isCanonical) { return }
+ const result = snapshot as { session_id: string; authority_epoch: number; prompts?: Array<Record<string, unknown>> }
+ for (const prompt of result.prompts ?? []) {
+ this.publishLocalEvent({ type: `${prompt.kind}.request`, session_id: result.session_id,
+ payload: { ...prompt, execution_epoch: String(result.authority_epoch) } } as unknown as GatewayEvent)
+ }
+ }
+
publishLocalEvent(ev: GatewayEvent) {
const frame = JSON.stringify({ jsonrpc: '2.0', method: 'event', params: ev })
@@ -530,7 +542,8 @@ export class GatewayClient extends EventEmitter {
this.clearReconnect()
this.connectSidecarMirror()
if (this.isCanonical) {
- void this.requestOverWebSocket('runtime.describe').then(() => {
+ void this.requestOverWebSocket<{session_create: CreationContract}>('runtime.describe').then(description => {
+ this.creationContract = description.session_create
if (this.ws === ws) { this.publish({ type: 'gateway.ready', payload: {} }) }
}).catch(error => {
this.publish({ type: 'gateway.start_timeout', payload: {
@@ -652,6 +665,11 @@ export class GatewayClient extends EventEmitter {
const ev = asGatewayEvent(msg.params)
if (ev) {
+ if (this.isCanonical) {
+ const shared = ev as GatewayEvent & { authority_epoch?: number; execution_generation?: number }
+ ev.payload = { ...ev.payload, execution_epoch: String(shared.authority_epoch),
+ execution_generation: shared.execution_generation } as any
+ }
this.publish(ev)
}
}
@@ -831,7 +849,8 @@ export class GatewayClient extends EventEmitter {
if (!this.bootstrapFlight) { this.start() }
return this.bootstrapFlight!.then(() => {
if (this.bootstrapError) { throw this.bootstrapError }
- return this.requestOverWebSocket<T>(method, params)
+ const request = canonicalRequest(method, params, this.creationContract)
+ return this.requestOverWebSocket<T>(request.method, request.params).then(value => canonicalResult(method, value))
})
}
diff --git a/ui-tui/src/types.ts b/ui-tui/src/types.ts
index 4fbdf5b67ac..9a300641b45 100644
--- a/ui-tui/src/types.ts
+++ b/ui-tui/src/types.ts
@@ -95,6 +95,7 @@ export interface DelegationStatus {
}
export interface ApprovalReq {
+ sharedControl?: import('./canonicalGateway.js').SharedControl
// false when the backend won't honor a permanent allow (tirith warning) → hide "Always allow".
allowPermanent?: boolean
choices?: string[]
@@ -120,6 +121,7 @@ export interface ClarifyBatchQuestion {
}
export interface ClarifyReq {
+ sharedControl?: import('./canonicalGateway.js').SharedControl
choices: string[] | null
question: string
requestId: string