run_api.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. """The gateway's local HTTP/WS listener: the native session WebSocket plus the dashboard API.
  2. The caller initializes session authority before starting this listener and owns
  3. all runtime services and signals. This module owns only HTTP resources; it does
  4. not bootstrap an agent, scheduler, hosted room, or a second gateway.
  5. The native session WebSocket (ticketed ``/api/ws`` — every local CLI/TUI/Desktop session) is served
  6. without the dashboard app: importing ``hermes_cli.web_server`` (about 690 routes, ~0.6 s) before the
  7. listener bound stalled every cold start and the control socket's identify. The dashboard is mounted
  8. on its first request (imported off the event loop) or warmed after READY for a supervised gateway
  9. (``warm_gateway_dashboard``); a gated listener (non-loopback bind, ``webapp.public_url`` on the Webapp's,
  10. ``dashboard.public_url`` on the private one) and a
  11. process that already imported it mount it before the listener starts, exactly as before.
  12. """
  13. import asyncio
  14. from dataclasses import dataclass
  15. import logging
  16. import os
  17. import socket
  18. import sys
  19. import types
  20. from typing import Any
  21. logger = logging.getLogger(__name__)
  22. # One listener per process: the dashboard routers share one process-local app.
  23. _ACTIVE_RUNNER: Any = None
  24. # A fixed port (the Webapp's) has to bind again while the last gateway's closed connections sit in
  25. # TIME_WAIT. POSIX allows that with SO_REUSEADDR; on Windows that option lets another process bind
  26. # the same port, and a rebind there does not wait on TIME_WAIT anyway.
  27. _REUSE_FIXED_PORT = os.name != "nt"
  28. # On Windows a fixed port is held for exclusive use instead: otherwise another process may bind it with
  29. # SO_REUSEADDR, and a more specific address (127.0.0.1 under a 0.0.0.0 bind) then takes its connections.
  30. _EXCLUSIVE_FIXED_PORT = os.name == "nt"
  31. @dataclass
  32. class GatewayAPIHandle:
  33. api_origin: str
  34. server: Any
  35. task: asyncio.Task
  36. app: Any
  37. socket: socket.socket
  38. class GatewayDashboardMount:
  39. """ASGI app that imports and mounts the dashboard (``hermes_cli.web_server.app``) on first use.
  40. ``state`` is the listener's boundary state (``bound_host``, ``bound_port``, ``auth_required``,
  41. ``trusted_public_hosts``, ``gateway_runner``, ``session_authority``) — what the native WebSocket
  42. path checks, mirrored onto the dashboard app state once it is mounted. ``state.webapp`` (a
  43. ``gateway.webapp_listener.WebappMount``) makes the mount serve the browser-hosted Desktop.
  44. """
  45. def __init__(self, runner, state):
  46. self.runner, self._state = runner, state
  47. self.web = None
  48. self._lock: asyncio.Lock | None = None
  49. self._lifespan = None
  50. self._closed = False
  51. self._replaced_session_token = None
  52. self._undo_own_sign_in = None
  53. @property
  54. def loaded(self) -> bool:
  55. return self.web is not None
  56. @property
  57. def state(self):
  58. """Boundary state: the dashboard app's own state once mounted (operators and tests may
  59. change it there), the listener's pre-mount snapshot before."""
  60. return self.web.app.state if self.web is not None else self._state
  61. def _bind_state(self, web) -> None:
  62. webapp = getattr(self._state, "webapp", None)
  63. # The browser credential before any app state: one the home cannot store fails the mount
  64. # with nothing set, and the gateway falls back to its private listener.
  65. token = None
  66. if webapp is not None:
  67. from gateway.webapp_listener import browser_session_token
  68. token = browser_session_token(webapp.home)
  69. # Local clients authenticate with tickets minted on the owner-only control socket. The SPA
  70. # session token is a bearer credential any loopback peer (any OS user) could read from
  71. # GET /, so the gateway-hosted listener never publishes it.
  72. web.app.state.withhold_session_token = True
  73. own_url = _listener_public_url(webapp)
  74. if own_url is not None:
  75. web.app.state.listener_public_url = own_url
  76. elif hasattr(web.app.state, "listener_public_url"):
  77. delattr(web.app.state, "listener_public_url")
  78. if webapp is not None: # before the gate looks for a sign-in provider
  79. from gateway.webapp_listener import use_own_sign_in
  80. self._undo_own_sign_in = use_own_sign_in(webapp)
  81. web._configure_auth_gate(self._state.bound_host, False, None, None)
  82. web.app.state.gateway_runner = self.runner
  83. web.app.state.session_authority = getattr(self.runner, "session_authority", None)
  84. web.app.state.bound_host = self._state.bound_host
  85. web.app.state.bound_port = self._state.bound_port
  86. if webapp is not None:
  87. # The browser-hosted Desktop: its bundle at /, its routes (launch handoff, socket tickets,
  88. # host terminal) on, and the browser credential kept in the home so tabs survive a restart.
  89. # The page itself still never carries the credential (the webapp surface withholds it).
  90. web.app.state.ui_surface = "webapp"
  91. web.app.state.web_dist = webapp.dist
  92. web.app.state.webapp_home = webapp.home
  93. self._replaced_session_token = web._SESSION_TOKEN
  94. web._SESSION_TOKEN = token
  95. def _unbind_state(self) -> None:
  96. undo_own_sign_in, self._undo_own_sign_in = self._undo_own_sign_in, None
  97. if undo_own_sign_in is not None: # a listener mounted next signs in with the configured client
  98. undo_own_sign_in()
  99. if self.web is not None:
  100. self.web.app.state.gateway_runner = None
  101. self.web.app.state.session_authority = None
  102. self.web.app.state.withhold_session_token = False
  103. if hasattr(self.web.app.state, "listener_public_url"):
  104. delattr(self.web.app.state, "listener_public_url")
  105. if self._replaced_session_token is not None:
  106. # Removed, not cleared: a listener mounted next (the private one the gateway falls back
  107. # to) must find the app as main's listener does, with no surface, bundle or home set.
  108. for name in ("ui_surface", "web_dist", "webapp_home"):
  109. if hasattr(self.web.app.state, name):
  110. delattr(self.web.app.state, name)
  111. self.web._SESSION_TOKEN, self._replaced_session_token = self._replaced_session_token, None
  112. async def ensure(self):
  113. """Import (off the loop), bind and start the dashboard app once; returns ``web_server``."""
  114. if self.web is not None:
  115. return self.web
  116. if self._lock is None:
  117. self._lock = asyncio.Lock()
  118. async with self._lock:
  119. if self.web is not None:
  120. return self.web
  121. if self._closed:
  122. raise RuntimeError("gateway API stopped")
  123. import importlib
  124. web = sys.modules.get("hermes_cli.web_server") or await asyncio.to_thread(
  125. importlib.import_module, "hermes_cli.web_server")
  126. if self._closed: # the listener stopped while the import ran
  127. raise RuntimeError("gateway API stopped")
  128. if getattr(web.app.state, "gateway_runner", None) not in (None, self.runner):
  129. raise RuntimeError("gateway API already started")
  130. try:
  131. # A bind that fails partway (the auth gate refusing a gated bind, or the Webapp's
  132. # browser credential that cannot be read or written) is undone like a failed lifespan:
  133. # the listener the gateway falls back to finds the app as main's does.
  134. self._bind_state(web)
  135. lifespan = web.app.router.lifespan_context(web.app)
  136. await lifespan.__aenter__()
  137. if self._closed: # close() won while the lifespan started; it never saw this mount
  138. await lifespan.__aexit__(None, None, None)
  139. raise RuntimeError("gateway API stopped")
  140. except BaseException:
  141. self.web = web
  142. self._unbind_state()
  143. self.web = None
  144. raise
  145. self.web, self._lifespan = web, lifespan
  146. return web
  147. async def close(self) -> None:
  148. self._closed = True
  149. lifespan, self._lifespan = self._lifespan, None
  150. try:
  151. if lifespan is not None:
  152. await lifespan.__aexit__(None, None, None)
  153. finally:
  154. self._unbind_state()
  155. async def __call__(self, scope, receive, send):
  156. if scope["type"] not in {"http", "websocket"}:
  157. return
  158. try:
  159. web = await self.ensure()
  160. except Exception:
  161. logger.exception("Gateway dashboard API failed to load")
  162. if scope["type"] == "websocket":
  163. await send({"type": "websocket.close", "code": 1011})
  164. else:
  165. from starlette.responses import JSONResponse
  166. await JSONResponse({"error": "dashboard_unavailable"}, status_code=500)(scope, receive, send)
  167. return
  168. await web.app(scope, receive, send)
  169. def _listener_socket(family, kind, proto, port: int, *, dual_stack: bool = False) -> socket.socket:
  170. """The listener's unbound socket; a fixed *port* may bind again at once (``_REUSE_FIXED_PORT``)
  171. or is held exclusively (``_EXCLUSIVE_FIXED_PORT``). A *dual_stack* IPv6 socket (the ``::``
  172. wildcard) takes IPv4 connections too."""
  173. listener = socket.socket(family, kind, proto)
  174. if dual_stack:
  175. # "::" means every address, as Linux binds it by default. Windows binds IPv6 only otherwise:
  176. # IPv4 clients would never reach the Webapp, and the exclusive hold below would cover the
  177. # IPv6 port alone, leaving 0.0.0.0 on the same port to another program.
  178. listener.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
  179. if port and _REUSE_FIXED_PORT:
  180. listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  181. elif port and _EXCLUSIVE_FIXED_PORT:
  182. listener.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
  183. return listener
  184. def _listener_public_url(webapp) -> str | None:
  185. """The public URL the listener answers to: the Webapp's own ``webapp.public_url`` ("" for none),
  186. never ``dashboard.public_url``, which describes ``hermes dashboard``. None leaves main's listener
  187. reading ``dashboard.public_url``."""
  188. return None if webapp is None else webapp.public_url
  189. async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0, webapp=None) -> GatewayAPIHandle:
  190. global _ACTIVE_RUNNER
  191. from gateway.webapp_listener import dial_origin
  192. from hermes_cli.web_server_boundary import (
  193. _dashboard_public_hosts, listener_auth_required, public_hosts_engage_gate, public_url_hosts,
  194. should_require_auth,
  195. )
  196. from hermes_cli.web_server_lifecycle import build_listener_server
  197. # Existing routers/auth helpers share one process-local app. Never rebind it
  198. # underneath another listener. Each authority is bound to its own profile DB.
  199. loaded_web = sys.modules.get("hermes_cli.web_server")
  200. if _ACTIVE_RUNNER is not None or (
  201. loaded_web is not None and getattr(loaded_web.app.state, "gateway_runner", None) is not None):
  202. raise RuntimeError("gateway API already started")
  203. public_url = _listener_public_url(webapp)
  204. if public_url is None:
  205. trusted = _dashboard_public_hosts()
  206. auth_required = listener_auth_required(host, trusted)
  207. else:
  208. # What web_server._configure_auth_gate decides for a listener that declares its public URL.
  209. trusted = public_url_hosts(public_url)
  210. auth_required = should_require_auth(host) or public_hosts_engage_gate(trusted)
  211. state = types.SimpleNamespace(
  212. bound_host=host, bound_port=None, auth_required=auth_required,
  213. trusted_public_hosts=trusted, gateway_runner=runner,
  214. session_authority=getattr(runner, "session_authority", None), webapp=webapp)
  215. mount = GatewayDashboardMount(runner, state)
  216. # Lifespan off: the dashboard's own lifespan runs when it is mounted (GatewayDashboardMount).
  217. config, server = build_listener_server(mount, host, port, auth_required=state.auth_required,
  218. timeout_graceful_shutdown=5, lifespan="off")
  219. family, kind, proto, _, address = socket.getaddrinfo(
  220. host, port, type=socket.SOCK_STREAM,
  221. )[0]
  222. listener = _listener_socket(family, kind, proto, port,
  223. dual_stack=family == socket.AF_INET6 and address[0] == "::")
  224. _ACTIVE_RUNNER = runner
  225. try:
  226. listener.bind(address)
  227. if port:
  228. # Under SO_REUSEADDR another socket may bind a fixed port too, and the first to listen
  229. # owns it. Listening now settles that before the dashboard mounts, so a lost race falls
  230. # back at once instead of after the mount is up.
  231. listener.listen(config.backlog)
  232. listener.setblocking(False)
  233. state.bound_port = listener.getsockname()[1]
  234. # Loading the ASGI graph may fail too; it owns the same bound socket.
  235. if not config.loaded:
  236. config.load()
  237. config.loaded_app = GatewayRuntimeAPI(config.loaded_app, runner, mount)
  238. # A gated listener needs the dashboard's auth providers (and refuses to start without one);
  239. # an already-imported dashboard costs nothing to mount now; the Webapp serves its page and
  240. # mints launch links from the start.
  241. if state.auth_required or loaded_web is not None or webapp is not None:
  242. await mount.ensure()
  243. server.lifespan = config.lifespan_class(config)
  244. await server.startup(sockets=[listener])
  245. if not server.started or server.should_exit:
  246. raise RuntimeError("gateway API lifespan startup failed")
  247. except BaseException:
  248. listener.close()
  249. _ACTIVE_RUNNER = None
  250. await mount.close()
  251. raise
  252. async def serve():
  253. global _ACTIVE_RUNNER
  254. try:
  255. await server.main_loop()
  256. finally:
  257. try:
  258. await server.shutdown(sockets=[listener])
  259. finally:
  260. listener.close()
  261. try:
  262. await mount.close()
  263. finally:
  264. _ACTIVE_RUNNER = None
  265. task = asyncio.create_task(serve(), name="gateway-api")
  266. return GatewayAPIHandle(
  267. # The address the socket bound, never a name: native clients accept only a numeric loopback
  268. # origin, and ``localhost`` may resolve to either family.
  269. api_origin=dial_origin(listener.getsockname()[0], state.bound_port),
  270. server=server, task=task, app=mount, socket=listener,
  271. )
  272. def warm_gateway_dashboard(runner) -> None:
  273. """Mount the dashboard in the background once the gateway is READY (supervised gateways, whose
  274. clients — Desktop, the dashboard SPA — call its routes right away). Never raises."""
  275. handle = getattr(runner, "session_api", None)
  276. mount = getattr(handle, "app", None)
  277. if not isinstance(mount, GatewayDashboardMount) or mount.loaded:
  278. return
  279. async def _warm():
  280. try:
  281. await mount.ensure()
  282. except Exception:
  283. if not mount._closed:
  284. logger.warning("Gateway dashboard API warm-up failed; it loads on first request", exc_info=True)
  285. runner._gateway_dashboard_warmup = asyncio.get_running_loop().create_task(
  286. _warm(), name="gateway-dashboard-warmup")
  287. async def stop_gateway_api(handle: GatewayAPIHandle) -> None:
  288. """Drain sockets without stopping the session authority or taking signals."""
  289. handle.server.should_exit = True
  290. # The bootstrap supervisor reports listener failure. Cleanup must still
  291. # reach adapter/worker settlement when that listener raised or was cancelled.
  292. await asyncio.shield(asyncio.gather(handle.task, return_exceptions=True))
  293. def _embedded_chat_enabled() -> bool:
  294. """``web_server._DASHBOARD_EMBEDDED_CHAT_ENABLED`` without importing the dashboard (always True
  295. unless a loaded dashboard says otherwise)."""
  296. web = sys.modules.get("hermes_cli.web_server")
  297. return True if web is None else bool(getattr(web, "_DASHBOARD_EMBEDDED_CHAT_ENABLED", True))
  298. def _restart_wait_read(runner, scope) -> bool:
  299. from gateway.drain_control import restart_wait_read
  300. return scope['type'] == 'http' and restart_wait_read(runner, scope.get('method'), scope.get('path'))
  301. def _restart_wait_socket_ticket(runner, scope) -> bool:
  302. from gateway.drain_control import restart_wait_socket_ticket
  303. return scope['type'] == 'http' and restart_wait_socket_ticket(
  304. runner, scope.get('method'), scope.get('path'), scope.get('query_string', b'').decode('latin-1'))
  305. class GatewayRuntimeAPI:
  306. """Redeem private local tickets at the existing WS subprotocol boundary.
  307. Other credentials and HTTP routes retain the complete dashboard gate. Local
  308. bootstrap never grants an exposure/worker ticket interactive permissions.
  309. *web_app* is the dashboard mount (or any object whose ``state`` carries the listener's
  310. ``bound_host`` / ``auth_required`` / ``trusted_public_hosts``).
  311. """
  312. def __init__(self, app, runner, web_app):
  313. self.app, self.runner, self.web_app = app, runner, web_app
  314. async def __call__(self, scope, receive, send):
  315. if scope['type'] != 'websocket' or scope.get('path') != '/api/ws':
  316. return await self._serve(scope, receive, send)
  317. started = accepted = False
  318. async def send_watched(message):
  319. nonlocal started, accepted
  320. started = True
  321. accepted = accepted or message.get('type') == 'websocket.accept'
  322. await send(message)
  323. try:
  324. return await self._serve(scope, receive, send_watched)
  325. except Exception as exc:
  326. # Uvicorn answers an upgrade that raised before accept with HTTP 500 and logs it only to
  327. # its own logger, never gateway.log: the dialing cron worker or managed worker sees a bare
  328. # InvalidStatus (#139922). Name the cause here; uvicorn still sends the 500, but only when
  329. # nothing was sent yet: a handler that had closed the upgrade already got its 403 out.
  330. if not accepted:
  331. logger.error('Gateway refused a session WebSocket upgrade from %s %s: %s: %s',
  332. scope.get('hermes.gateway_socket_peer') or scope.get('client'),
  333. 'after its handler had refused it' if started else 'with HTTP 500',
  334. type(exc).__name__, exc, exc_info=True)
  335. raise
  336. async def _serve(self, scope, receive, send):
  337. descriptor = getattr(self.runner, 'session_runtime_descriptor', None)
  338. if scope['type'] not in {'http', 'websocket'} or descriptor is None:
  339. return await self.app(scope, receive, send)
  340. draining_socket = (descriptor['state'] in {'ready', 'draining'}
  341. and (self.runner._draining or descriptor['state'] == 'draining')
  342. and scope['type'] == 'websocket' and scope['path'] == '/api/ws')
  343. if ((descriptor['state'] != 'ready' or self.runner._draining) and not draining_socket
  344. and not _restart_wait_read(self.runner, scope)
  345. and not _restart_wait_socket_ticket(self.runner, scope)):
  346. if scope['type'] == 'websocket':
  347. await send({'type': 'websocket.close', 'code': 1013})
  348. else:
  349. from starlette.responses import JSONResponse
  350. await JSONResponse({'error': 'gateway_not_ready', 'state': descriptor['state']},
  351. status_code=503)(scope, receive, send)
  352. return
  353. # Capture before Uvicorn's proxy middleware rewrites scope.client (native grants, both kinds).
  354. scope['hermes.gateway_socket_peer'] = scope.get('client')
  355. from gateway.run_idle_exit import attached_client, note_client_activity
  356. if scope['type'] != 'websocket' or scope['path'] != '/api/ws':
  357. note_client_activity(self.runner) # dashboard/API traffic keeps an idle-exit gateway up
  358. return await self.app(scope, receive, send)
  359. original_receive = receive
  360. allow_draining = False
  361. admitted_in_wait = False
  362. from gateway.drain_control import restart_wait_open
  363. async def receive_admitted():
  364. message = await original_receive()
  365. # Only a socket admitted INTO the restart wait (to answer a parked prompt) outlives it. One
  366. # opened before the wait is cut as before: its client reconnects to the next owner, and a
  367. # held one (a kanban worker polling its card) would otherwise pin the drain to its cap.
  368. if ((descriptor['state'] != 'ready' or self.runner._draining) and not allow_draining
  369. and not (admitted_in_wait and restart_wait_open(self.runner))):
  370. return {'type': 'websocket.disconnect', 'code': 1013}
  371. return message
  372. receive = receive_admitted
  373. from starlette.websockets import WebSocket
  374. from hermes_cli.web_server_boundary import (
  375. _gateway_ws_ticket_from_subprotocol, ws_client_reason, ws_host_origin_reason,
  376. )
  377. state = getattr(self.web_app, 'state', None)
  378. scope['app'] = self.web_app
  379. ws = WebSocket(scope, receive, send)
  380. ticket, reason = _gateway_ws_ticket_from_subprotocol(ws)
  381. # Native grants are loopback-only, so a remote ticket is the Webapp's (the mobile app sends no
  382. # Origin, #147361). Origin is client-controlled, so this reaches no gate an Origin could not.
  383. native_peer = bool(ws.client) and ws.client.host in {'127.0.0.1', '::1'}
  384. if reason == 'none' or ws.headers.get('origin') or (reason == 'ok' and not native_peer):
  385. if draining_socket:
  386. # Let a Webapp tab's ticket reach its normal upgrade gate during restart wait: only a
  387. # surface that mints browser tickets redeems one there (elsewhere the loopback gate
  388. # takes ``?token=``).
  389. from hermes_cli.web_server_surface import policy
  390. admitted_in_wait = (reason == 'ok' and 'internal' not in ws.query_params
  391. and policy(state).gateway_ticket
  392. and restart_wait_open(self.runner))
  393. if not admitted_in_wait:
  394. await ws.close(code=1013)
  395. return
  396. return await self.app(scope, receive, send)
  397. if (reason != 'ok' or not _embedded_chat_enabled()
  398. or ws_host_origin_reason(ws, state) is not None or ws_client_reason(ws, state) is not None
  399. or ws.headers.get('origin') or not native_peer):
  400. await ws.close(code=4403)
  401. return
  402. operator = True
  403. try:
  404. grant = self.runner.session_ticket_store.redeem(ticket, profile_id=None, purpose='interactive')
  405. except PermissionError:
  406. operator = False
  407. try:
  408. grant = self.runner.session_ticket_store.redeem(ticket, profile_id=None, purpose='worker-adoption')
  409. except PermissionError:
  410. # Browser/OAuth tickets have a separate issuer.
  411. if draining_socket:
  412. await ws.close(code=1013)
  413. return
  414. return await self.app(scope, receive, send)
  415. allow_draining = not operator
  416. # Decided here, at admission, not at the mint: a restart wait that opened after the client's
  417. # discovery still refuses the machine poller that asked to stay out of it (a Kanban worker),
  418. # which would otherwise hold the turn the wait is waiting on.
  419. admitted_in_wait = restart_wait_open(self.runner) and not grant.get('refuse_restart_wait')
  420. # A restart's after-turn wait still owns its turns: an interactive client attaches to answer
  421. # a parked approval/clarify (#139041); stop() closes this window.
  422. if ((descriptor['state'] != 'ready' or self.runner._draining) and not allow_draining
  423. and not admitted_in_wait):
  424. await ws.close(code=1013)
  425. return
  426. from gateway.session_authorities import authority_for_profile_id
  427. authority = authority_for_profile_id(self.runner, grant['profile_id'])
  428. if authority is None:
  429. await ws.close(code=4403)
  430. return
  431. # The ticket names the served profile; this connection binds to that home's authority.
  432. scope['hermes.session_authority'] = authority
  433. from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL
  434. from tui_gateway.ws import handle_ws
  435. from gateway.session_authorities import owner_scope
  436. with owner_scope(authority), attached_client(self.runner):
  437. await handle_ws(ws, auth_identity={'user_id': grant['subject'], 'provider': 'local',
  438. 'profile_id': grant['profile_id'],
  439. 'instance_id': grant['instance_id'],
  440. 'capabilities': grant['capabilities'], 'native_bootstrap': True,
  441. 'profile_scope': grant.get('scope', 'profile')},
  442. subprotocol=CANONICAL_GATEWAY_PROTOCOL, operator=operator)