bridge_runtime.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. """Process-private, session-scoped tool capabilities for Hermes v0.21.0.
  2. Only this canonical module owns bindings. Nothing is written into prompts,
  3. global MCP settings, the Hermes environment or persistent session metadata.
  4. """
  5. from __future__ import annotations
  6. import base64
  7. import hmac
  8. import hashlib
  9. import json
  10. import math
  11. import mimetypes
  12. import os
  13. import re
  14. import sys
  15. import threading
  16. import time
  17. import urllib.error
  18. import urllib.parse
  19. import urllib.request
  20. import uuid
  21. from dataclasses import dataclass, field
  22. from pathlib import Path
  23. from typing import Any
  24. VERSION = 1
  25. MAX_LEASE_MS = 30 * 60 * 1000
  26. MAX_RESPONSE_BYTES = 64 * 1024 * 1024
  27. registered = False
  28. _lock = threading.RLock()
  29. _bindings: dict[str, "Binding"] = {}
  30. # Remember revoked generations while the live gateway object exists so an old
  31. # HTTP bind arriving after unbind cannot reinstate an obsolete capability.
  32. _generations: dict[str, tuple[dict, set[str]]] = {}
  33. _contexts: dict[Path, Any] = {}
  34. _children: dict[str, tuple["Binding", Any]] = {}
  35. class BridgeError(Exception):
  36. def __init__(self, message: str, status: int = 403, code: str = "forbidden"):
  37. super().__init__(message)
  38. self.status = status
  39. self.code = code
  40. @dataclass(repr=False)
  41. class Binding:
  42. session_id: str
  43. stored_session_id: str
  44. profile: str
  45. profile_home: Path
  46. generation: str
  47. bridge_url: str
  48. token: str
  49. expires_at: float
  50. owner: tuple[str, str]
  51. session: dict
  52. agent: Any
  53. toolset: str = ""
  54. registrations: list = field(default_factory=list)
  55. native_names: set = field(default_factory=set)
  56. catalog_fingerprint: str = ""
  57. sampling: dict = field(default_factory=dict)
  58. computer_policy: dict | None = None
  59. def register_context(ctx):
  60. from hermes_constants import get_hermes_home
  61. _contexts[Path(get_hermes_home()).resolve()] = ctx
  62. if callable(getattr(ctx, "register_hook", None)):
  63. ctx.register_hook("subagent_start", inherit_child)
  64. ctx.register_hook("subagent_stop", release_child)
  65. ctx.register_hook("pre_tool_call", refresh_catalog)
  66. ctx.register_hook("pre_tool_call", computer_directive)
  67. def _refresh_agent_tools(agent, binding):
  68. from model_tools import get_tool_definitions, get_toolset_for_tool
  69. if not hasattr(agent, "_yaoyao_base_toolsets"):
  70. agent._yaoyao_base_toolsets = getattr(agent, "enabled_toolsets", None)
  71. base = agent._yaoyao_base_toolsets
  72. definitions = get_tool_definitions(enabled_toolsets=base,
  73. disabled_toolsets=getattr(agent, "disabled_toolsets", None), quiet_mode=True,
  74. skip_tool_search_assembly=True) or []
  75. # Expand wildcard scopes before adding a private lease. Otherwise an
  76. # `all` Agent's Tool Search could enumerate another Bot's dynamic schemas.
  77. enabled = sorted({toolset for tool in definitions
  78. if (toolset := get_toolset_for_tool(tool.get("function", {}).get("name", "")))
  79. and not toolset.startswith("yaoyao_turn_")})
  80. if binding.toolset and binding.toolset not in enabled:
  81. enabled.append(binding.toolset)
  82. agent.enabled_toolsets = enabled
  83. agent.tools = get_tool_definitions(enabled_toolsets=enabled,
  84. disabled_toolsets=getattr(agent, "disabled_toolsets", None), quiet_mode=True) or []
  85. agent.valid_tool_names = {tool["function"]["name"] for tool in agent.tools}
  86. if hasattr(agent, "_memory_manager"):
  87. from agent.memory_manager import inject_memory_provider_tools
  88. inject_memory_provider_tools(agent)
  89. invalidate = getattr(agent, "_invalidate_system_prompt", None)
  90. if callable(invalidate):
  91. invalidate()
  92. def _retire(binding):
  93. for child_id, (owner, _) in list(_children.items()):
  94. if owner is binding:
  95. _children.pop(child_id, None)
  96. for registration in reversed(binding.registrations):
  97. if registration is not None:
  98. registration.dispose()
  99. binding.registrations.clear()
  100. if binding.toolset:
  101. if hasattr(binding.agent, "_yaoyao_base_toolsets"):
  102. binding.agent.enabled_toolsets = binding.agent._yaoyao_base_toolsets
  103. del binding.agent._yaoyao_base_toolsets
  104. def inherit_child(parent_session_id=None, child_session_id=None, **kwargs):
  105. """Only the core lifecycle can introduce a child; model args cannot."""
  106. try:
  107. binding = _resolve(parent_session_id)
  108. inherited = _children.get(parent_session_id) or next((entry for entry in _children.values() if getattr(entry[1], "session_id", None) == parent_session_id), None)
  109. parent = inherited[1] if inherited else binding.agent
  110. child = next((item for item in getattr(parent, "_active_children", [])
  111. if getattr(item, "session_id", None) == child_session_id), None)
  112. if child is None or not child_session_id:
  113. return
  114. with _lock:
  115. _children[child_session_id] = (binding, child)
  116. _refresh_agent_tools(child, binding)
  117. except BridgeError:
  118. return
  119. def release_child(child_session_id=None, **kwargs):
  120. with _lock:
  121. for key, (_, child) in list(_children.items()):
  122. if key == child_session_id or getattr(child, "session_id", None) == child_session_id:
  123. _children.pop(key, None)
  124. def refresh_catalog(session_id=None, function_name=None, tool_name=None, **kwargs):
  125. if (function_name or tool_name) not in {"tool_search", "tool_describe", "yaoyao_tools"}:
  126. return
  127. try:
  128. binding = _resolve(session_id)
  129. if binding.toolset:
  130. with _lock:
  131. _mount_native_tools(binding)
  132. except BridgeError:
  133. return
  134. def _mount_native_tools(binding):
  135. """Register session-scoped schemas in Hermes' own searchable catalog."""
  136. ctx = _contexts.get(binding.profile_home)
  137. if ctx is None:
  138. raise BridgeError("请安装新版工具桥并重新打开 Hermes 会话", 409, "tools_unavailable")
  139. catalog = _request(binding, "/tools/list")
  140. fingerprint = hashlib.sha256(json.dumps(catalog.get("tools", []), sort_keys=True).encode()).hexdigest()
  141. if fingerprint == binding.catalog_fingerprint:
  142. return
  143. for registration in reversed(binding.registrations):
  144. registration.dispose()
  145. binding.registrations.clear()
  146. binding.native_names.clear()
  147. binding.toolset = "yaoyao_turn_" + hashlib.sha256(binding.generation.encode()).hexdigest()[:16]
  148. for tool in catalog.get("tools", []):
  149. tool_id = _string(tool, "id")
  150. label = _string(tool, "name")
  151. name = "yaoyao_" + re.sub(r"[^a-zA-Z0-9_]", "_", label)[:30] + "_" + hashlib.sha256(tool_id.encode()).hexdigest()[:12]
  152. description = f"夭夭 Bot {label}。" + str(tool.get("description") or "")
  153. def handler(args, _tool_id=tool_id, **kwargs):
  154. try:
  155. if _resolve(kwargs.get("session_id", "")) is not binding:
  156. raise BridgeError("此工具属于其他轮次,授权已失效")
  157. return call_tool({"toolId": _tool_id, "arguments": args}, **kwargs)
  158. except BridgeError as exc:
  159. return json.dumps({"error": str(exc), "code": exc.code}, ensure_ascii=False)
  160. handle = ctx.register_tool(name=name, toolset=binding.toolset, description=description,
  161. schema={"name": name, "description": description, "parameters": tool.get("inputSchema") or {"type": "object", "properties": {}}}, handler=handler)
  162. if handle is None:
  163. raise BridgeError("Hermes 无法注册本轮工具", 503, "unsupported_runtime")
  164. binding.registrations.append(handle)
  165. binding.native_names.add(name)
  166. _refresh_agent_tools(binding.agent, binding)
  167. for owner, child in list(_children.values()):
  168. if owner is binding:
  169. _refresh_agent_tools(child, binding)
  170. binding.catalog_fingerprint = fingerprint
  171. async def sampling_request(owner, body):
  172. """Reuse Hermes' bounded native MCP sampling, scoped to this turn/profile."""
  173. binding = _resolve(_string(body, "session_id"))
  174. if binding.owner != owner or binding.generation != _string(body, "generation"):
  175. raise BridgeError("采样请求不属于当前轮次")
  176. name = _string(body, "server", 128)
  177. params = body.get("params")
  178. if not isinstance(params, dict):
  179. raise BridgeError("采样请求格式无效", 400)
  180. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  181. from tools.mcp_tool import SamplingHandler, _ensure_mcp_sdk
  182. _ensure_mcp_sdk()
  183. from mcp.types import CreateMessageRequestParams
  184. parsed = CreateMessageRequestParams.model_validate(params)
  185. context = set_hermes_home_override(binding.profile_home)
  186. try:
  187. handler = binding.sampling.setdefault(name, SamplingHandler(name, {"max_rpm": 10, "timeout": 30, "max_tokens_cap": 4096}))
  188. result = await handler(None, parsed)
  189. if _resolve(binding.session_id) is not binding:
  190. raise BridgeError("采样结果所属轮次已经结束")
  191. return result.model_dump(by_alias=True, exclude_none=True)
  192. finally:
  193. reset_hermes_home_override(context)
  194. def _web():
  195. # This module must execute inside the real Dashboard. Never create a new
  196. # Dashboard with a new auth token when a plugin is imported in another host.
  197. web = sys.modules.get("hermes_cli.web_server")
  198. if web is None or not callable(getattr(web, "_has_valid_session_token", None)):
  199. raise BridgeError("当前进程不是受支持的 Hermes Dashboard", 503, "unsupported_runtime")
  200. return web
  201. def _server():
  202. try:
  203. from tui_gateway import server
  204. except ImportError:
  205. raise BridgeError("Hermes 会话接口不可用", 503, "unsupported_runtime") from None
  206. if not isinstance(getattr(server, "_sessions", None), dict) or not hasattr(server, "_sessions_lock"):
  207. raise BridgeError("Hermes 会话接口不兼容,请修复工具桥或更新 Hermes", 503, "unsupported_runtime")
  208. if not callable(getattr(server, "_turn_isolation_enabled", None)):
  209. raise BridgeError("无法确认 Hermes 的运行模式", 503, "unsupported_runtime")
  210. try:
  211. isolated = server._turn_isolation_enabled()
  212. except Exception:
  213. raise BridgeError("无法确认 Hermes 的运行模式", 503, "unsupported_runtime") from None
  214. if isolated:
  215. raise BridgeError("工具桥仅支持 Hermes 非隔离运行模式", 503, "unsupported_mode")
  216. return server
  217. def request_identity(request) -> tuple[str, str]:
  218. """Use only the core HTTP gate's verified principal, never request JSON."""
  219. web = _web()
  220. if bool(getattr(web.app.state, "auth_required", False)):
  221. session = getattr(request.state, "session", None)
  222. user = getattr(session, "user_id", None)
  223. provider = getattr(session, "provider", None)
  224. if not isinstance(user, str) or not user or not isinstance(provider, str) or not provider:
  225. raise BridgeError("请先登录 Hermes Dashboard", 401, "unauthorized")
  226. if provider == "server-internal" or getattr(session, "expires_at", 0) <= time.time():
  227. raise BridgeError("Hermes 登录已过期", 401, "unauthorized")
  228. return provider, user
  229. if not web._has_valid_session_token(request):
  230. raise BridgeError("Hermes 本机令牌无效", 401, "unauthorized")
  231. return "local-session-token", "dashboard"
  232. def _transport_identity(transport) -> tuple[str, str]:
  233. from tui_gateway.ws import WSTransport
  234. if not isinstance(transport, WSTransport):
  235. raise BridgeError("仅支持已认证的 Dashboard WebSocket 会话")
  236. identity = getattr(transport, "auth_identity", None)
  237. web = _web()
  238. if bool(getattr(web.app.state, "auth_required", False)):
  239. if not isinstance(identity, dict):
  240. raise BridgeError("WebSocket 会话缺少可信身份")
  241. user, provider = identity.get("user_id"), identity.get("provider")
  242. if not isinstance(user, str) or not user or not isinstance(provider, str) or not provider or provider == "server-internal":
  243. raise BridgeError("WebSocket 会话身份不受支持")
  244. return provider, user
  245. # Identity None alone is not authority: stdio and unauthenticated fakes also
  246. # have no identity. Require the canonical token on the admitted WS object.
  247. ws = getattr(transport, "_ws", None)
  248. token = getattr(ws, "query_params", {}).get("token", "")
  249. expected = getattr(web, "_SESSION_TOKEN", "")
  250. if identity is not None or not isinstance(token, str) or not expected or not hmac.compare_digest(token, expected):
  251. raise BridgeError("WebSocket 会话与本机登录不匹配")
  252. return "local-session-token", "dashboard"
  253. def capabilities(profile: str = "default") -> dict:
  254. in_process = False
  255. try:
  256. _web()
  257. if not isinstance(profile, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", profile):
  258. raise BridgeError("Profile 名称无效", 400, "invalid_profile")
  259. from hermes_cli.profiles import get_profile_dir, profile_exists
  260. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  261. if not profile_exists(profile):
  262. raise BridgeError("Hermes Profile 不存在", 404, "profile_missing")
  263. home = get_profile_dir(profile)
  264. # Dashboard APIs mount independently of the lazy tool-plugin loader.
  265. from hermes_cli.plugins import discover_plugins
  266. from hermes_cli.config import load_config
  267. from model_tools import get_tool_definitions
  268. context = set_hermes_home_override(home)
  269. try:
  270. server = _server()
  271. in_process = True
  272. discover_plugins()
  273. config = load_config()
  274. agent_config = config.get("agent") or {}
  275. definitions = get_tool_definitions(
  276. enabled_toolsets=server._load_enabled_toolsets(),
  277. disabled_toolsets=agent_config.get("disabled_toolsets") if isinstance(agent_config, dict) else None,
  278. quiet_mode=True, skip_tool_search_assembly=True,
  279. ) or []
  280. names = {t.get("function", {}).get("name") for t in definitions if isinstance(t, dict)}
  281. if not {"yaoyao_tools", "yaoyao_call"} <= names:
  282. raise BridgeError(f"Profile {profile} 尚未安装或启用夭夭工具桥,请检查该 Profile 的插件与工具集设置", 503, "profile_tools_unavailable")
  283. return {"version": VERSION, "ready": True, "in_process": True, "profile": profile, "native_tools": True,
  284. "computer_runtime_version": 2, "memory_isolation": True, "memory_extraction": True}
  285. finally:
  286. reset_hermes_home_override(context)
  287. except Exception as exc:
  288. reason = str(exc) if isinstance(exc, BridgeError) else "无法确认 Hermes 插件接口兼容性"
  289. return {"version": VERSION, "ready": False, "in_process": in_process, "profile": profile, "reason": reason}
  290. def _string(body: dict, key: str, maximum: int = 512) -> str:
  291. value = body.get(key)
  292. if not isinstance(value, str) or not value or len(value) > maximum or any(ord(c) < 32 for c in value):
  293. raise BridgeError(f"参数 {key} 无效", 400, "invalid_request")
  294. return value
  295. def _bridge_url(value: str) -> str:
  296. try:
  297. parsed = urllib.parse.urlsplit(value)
  298. port = parsed.port
  299. if (
  300. parsed.scheme != "http" or parsed.hostname != "127.0.0.1"
  301. or not port or not 1 <= port <= 65535
  302. or parsed.username is not None or parsed.password is not None
  303. or parsed.path or parsed.query or parsed.fragment
  304. or value != f"http://127.0.0.1:{port}"
  305. ):
  306. raise ValueError()
  307. except ValueError:
  308. raise BridgeError("工具桥地址必须是本机 127.0.0.1 的 HTTP 端口", 400, "invalid_request") from None
  309. return value
  310. def _profile_home(session: dict, profile: str) -> Path:
  311. from hermes_cli.profiles import get_profile_dir, profile_matches_home
  312. from hermes_constants import get_process_hermes_home
  313. actual = Path(session.get("profile_home") or get_process_hermes_home()).resolve()
  314. if not profile_matches_home(profile, actual):
  315. raise BridgeError("Profile 与 Hermes 会话不匹配")
  316. return Path(get_profile_dir(profile)).resolve()
  317. def _check_session_mode(session: dict) -> None:
  318. # A session created before the process-wide setting changed can still own
  319. # a compute host. Its worker cannot share this process-private table.
  320. if session.get("_compute_host_active"):
  321. raise BridgeError("此 Hermes 会话仍使用隔离计算进程,请在非隔离模式下新建会话", 503, "unsupported_mode")
  322. def _expiry(body: dict) -> float:
  323. value = body.get("expires_at")
  324. now = time.time() * 1000
  325. if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not now < value <= now + MAX_LEASE_MS + 5000:
  326. raise BridgeError("工具桥授权有效期无效", 400, "invalid_request")
  327. return value
  328. def _agent_has_tools(agent, home: Path) -> bool:
  329. required = {"yaoyao_tools", "yaoyao_call"}
  330. names = {
  331. t.get("function", {}).get("name")
  332. for t in (getattr(agent, "tools", None) or []) if isinstance(t, dict)
  333. }
  334. if required <= names:
  335. return True
  336. if not {"tool_call", "tool_describe"} <= names or not hasattr(agent, "enabled_toolsets") or not hasattr(agent, "disabled_toolsets"):
  337. return False
  338. # Current Hermes defers plugin schemas behind Tool Search. Check the same
  339. # scoped pre-assembly catalog its dispatcher uses, not process-global names
  340. # or text in the model-visible tool_search description.
  341. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  342. from model_tools import get_tool_definitions
  343. context = set_hermes_home_override(home)
  344. try:
  345. definitions = get_tool_definitions(
  346. enabled_toolsets=agent.enabled_toolsets,
  347. disabled_toolsets=agent.disabled_toolsets,
  348. quiet_mode=True, skip_tool_search_assembly=True,
  349. ) or []
  350. return required <= {t.get("function", {}).get("name") for t in definitions if isinstance(t, dict)}
  351. finally:
  352. reset_hermes_home_override(context)
  353. def _purge(server) -> None:
  354. now = time.time() * 1000
  355. for sid, binding in list(_bindings.items()):
  356. if binding.expires_at <= now or server._sessions.get(sid) is not binding.session:
  357. _bindings.pop(sid, None)
  358. _retire(binding)
  359. for sid, (session, _) in list(_generations.items()):
  360. if server._sessions.get(sid) is not session:
  361. _generations.pop(sid, None)
  362. for sid, (binding, _) in list(_children.items()):
  363. if _bindings.get(binding.session_id) is not binding:
  364. _children.pop(sid, None)
  365. def bind(owner: tuple[str, str], body: dict, *, wait_seconds: float = 20) -> dict:
  366. policy = body.get("computer_policy")
  367. if policy is not None and (not isinstance(policy, dict) or set(policy) != {"mode", "hostAccess"}
  368. or policy.get("mode") not in {"isolated", "profile"}
  369. or type(policy.get("hostAccess")) is not bool):
  370. raise BridgeError("电脑会话权限格式无效", 400, "invalid_computer_policy")
  371. server = _server()
  372. sid = _string(body, "session_id")
  373. stored = _string(body, "stored_session_id")
  374. profile = _string(body, "profile", 128)
  375. generation = _string(body, "generation", 128)
  376. url = _bridge_url(_string(body, "bridge_url", 128))
  377. token = _string(body, "token", 512)
  378. if len(token) < 32:
  379. raise BridgeError("工具桥令牌长度不足", 400, "invalid_request")
  380. expiry = _expiry(body)
  381. deadline = time.monotonic() + wait_seconds
  382. while True:
  383. with server._sessions_lock, _lock:
  384. session = server._sessions.get(sid)
  385. if not isinstance(session, dict):
  386. raise BridgeError("Hermes 会话不存在", 404, "session_missing")
  387. _check_session_mode(session)
  388. if _transport_identity(session.get("transport")) != owner:
  389. raise BridgeError("当前登录不能绑定此会话")
  390. home = _profile_home(session, profile)
  391. if session.get("_finalized"):
  392. raise BridgeError("Hermes 会话已经结束", 409, "session_closed")
  393. agent = session.get("agent")
  394. current = _bindings.get(sid)
  395. busy = bool(session.get("running")) and not (current and current.generation == generation)
  396. if agent is not None and not busy:
  397. break
  398. if time.monotonic() >= deadline:
  399. if busy:
  400. raise BridgeError("Hermes 会话正在运行,不能更换轮次授权", 409, "session_busy")
  401. raise BridgeError("Hermes 会话仍在初始化,请重试", 409, "initializing")
  402. time.sleep(0.1)
  403. with server._sessions_lock, _lock:
  404. _purge(server)
  405. expiry = _expiry(body)
  406. if server._sessions.get(sid) is not session or session.get("agent") is not agent:
  407. raise BridgeError("Hermes 会话已改变,请重试", 409, "session_changed")
  408. _check_session_mode(session)
  409. if _transport_identity(session.get("transport")) != owner or _profile_home(session, profile) != home:
  410. raise BridgeError("Hermes 会话身份或 Profile 已改变")
  411. current_keys = {str(session.get("session_key") or ""), str(getattr(agent, "session_id", "") or "")}
  412. if stored not in current_keys:
  413. raise BridgeError("持久会话 ID 与当前会话不匹配", 409, "session_changed")
  414. if not _agent_has_tools(agent, home):
  415. raise BridgeError("此会话尚未加载工具桥,请启用 yaoyao_bot_bridge 工具集并新建会话", 409, "tools_unavailable")
  416. current = _bindings.get(sid)
  417. if current and current.generation == generation:
  418. if current.session is not session or current.agent is not agent or current.owner != owner or current.profile != profile or current.bridge_url != url or current.computer_policy != policy or not hmac.compare_digest(current.token, token):
  419. raise BridgeError("不能更改现有轮次的工具授权", 409, "generation_conflict")
  420. current.expires_at = max(current.expires_at, expiry)
  421. current.stored_session_id = stored
  422. return {"ok": True, "generation": generation, "expires_at": current.expires_at,
  423. "native_tools": bool(current.toolset), "computer_runtime_version": 2}
  424. previous = _generations.get(sid)
  425. seen = previous[1] if previous and previous[0] is session else set()
  426. if generation in seen:
  427. raise BridgeError("该轮次授权已撤销", 409, "generation_revoked")
  428. if session.get("running"):
  429. raise BridgeError("Hermes 会话正在运行,不能更换轮次授权", 409, "session_busy")
  430. if len(seen) >= 4096:
  431. raise BridgeError("请恢复会话以更新工具桥授权记录", 409, "session_renewal_required")
  432. seen.add(generation)
  433. _generations[sid] = (session, seen)
  434. if current:
  435. _retire(current)
  436. binding = Binding(sid, stored, profile, home, generation, url, token, expiry, owner, session, agent)
  437. binding.computer_policy = dict(policy) if policy else None
  438. if policy:
  439. # Private runtime state survives unbind so a stale tool call cannot
  440. # fall back to the unrestricted native Profile after revocation.
  441. session["_yaoyao_computer_policy"] = dict(policy)
  442. _bindings[sid] = binding
  443. if body.get("native_tools") is True:
  444. try:
  445. _mount_native_tools(binding)
  446. except Exception:
  447. _bindings.pop(sid, None)
  448. _retire(binding)
  449. raise
  450. return {"ok": True, "generation": generation, "expires_at": expiry, "native_tools": bool(binding.toolset),
  451. "computer_runtime_version": 2}
  452. def unbind(owner: tuple[str, str], body: dict) -> dict:
  453. server = _server()
  454. sid, generation = _string(body, "session_id"), _string(body, "generation", 128)
  455. with server._sessions_lock, _lock:
  456. _purge(server)
  457. binding = _bindings.get(sid)
  458. if binding is None:
  459. return {"ok": True, "removed": False}
  460. if binding.owner != owner:
  461. raise BridgeError("当前登录不能撤销此会话的授权")
  462. if binding.generation != generation:
  463. return {"ok": True, "removed": False}
  464. _bindings.pop(sid, None)
  465. _retire(binding)
  466. return {"ok": True, "removed": True}
  467. def _resolve(session_id: str) -> Binding:
  468. # session_id is supplied by Hermes' tool dispatcher kwargs, never args.
  469. if not isinstance(session_id, str) or not session_id:
  470. raise BridgeError("工具调用缺少可信 Hermes 会话身份")
  471. server = _server()
  472. with server._sessions_lock, _lock:
  473. _purge(server)
  474. inherited = _children.get(session_id)
  475. if inherited is None:
  476. inherited = next((value for value in _children.values() if getattr(value[1], "session_id", None) == session_id), None)
  477. if inherited:
  478. binding, child = inherited
  479. if _bindings.get(binding.session_id) is not binding or getattr(child, "session_id", None) != session_id:
  480. raise BridgeError("子代理工具授权已失效")
  481. session_id = binding.session_id
  482. matches = [
  483. (sid, session) for sid, session in server._sessions.items()
  484. if session_id in {
  485. sid, str(session.get("session_key") or ""),
  486. str(getattr(session.get("agent"), "session_id", "") or ""),
  487. }
  488. ]
  489. if len(matches) != 1:
  490. raise BridgeError("无法确定工具调用所属的唯一会话")
  491. sid, session = matches[0]
  492. _check_session_mode(session)
  493. binding = _bindings.get(sid)
  494. if binding is None:
  495. raise BridgeError("本轮没有可用的夭夭工具授权,或授权已经结束")
  496. if binding.session is not session or session.get("agent") is not binding.agent:
  497. raise BridgeError("Hermes 会话已更换,旧工具授权失效")
  498. if _transport_identity(session.get("transport")) != binding.owner or _profile_home(session, binding.profile) != binding.profile_home:
  499. raise BridgeError("工具调用的身份或 Profile 已改变")
  500. if not session.get("running") or session.get("_finalized"):
  501. raise BridgeError("本轮已经停止,工具授权不可使用")
  502. return binding
  503. class _NoRedirect(urllib.request.HTTPRedirectHandler):
  504. def redirect_request(self, req, fp, code, msg, headers, newurl):
  505. raise BridgeError("工具桥拒绝重定向", 502, "bridge_redirect")
  506. def _request(binding: Binding, path: str, body: dict | None = None) -> dict:
  507. remaining = (binding.expires_at - time.time() * 1000) / 1000
  508. if remaining <= 0:
  509. raise BridgeError("本轮工具授权已过期")
  510. request = urllib.request.Request(
  511. binding.bridge_url + path,
  512. data=json.dumps({} if body is None else body, ensure_ascii=False).encode(),
  513. headers={"Authorization": "Bearer " + binding.token, "Content-Type": "application/json"},
  514. method="POST",
  515. )
  516. # Loopback never uses machine proxy settings; redirects must not leak token.
  517. opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
  518. try:
  519. with opener.open(request, timeout=min(remaining, 600)) as response:
  520. raw = response.read(MAX_RESPONSE_BYTES + 1)
  521. if len(raw) > MAX_RESPONSE_BYTES:
  522. raise BridgeError("工具结果过大,请改用文件附件", 502, "result_too_large")
  523. result = json.loads(raw)
  524. if not isinstance(result, dict):
  525. raise ValueError()
  526. return result
  527. except urllib.error.HTTPError as exc:
  528. # Do not reflect upstream response/request objects: they can carry keys.
  529. raise BridgeError(f"工具桥拒绝请求(HTTP {exc.code})", 502, "bridge_rejected") from None
  530. except (urllib.error.URLError, TimeoutError, OSError):
  531. raise BridgeError("工具桥连接中断;操作可能已执行,请先检查结果,不要自动重试", 502, "bridge_unreachable") from None
  532. except (ValueError, UnicodeError):
  533. raise BridgeError("工具桥返回了无效结果", 502, "invalid_result") from None
  534. def _attachment(binding: Binding, data: bytes, mime: str) -> str:
  535. # Immutable UUID filenames, private directory and private files. Persist
  536. # outside conversations so file references survive Dashboard restarts.
  537. parent = binding.profile_home / "attachments"
  538. directory = parent / "yaoyao-bot-bridge"
  539. if parent.is_symlink() or directory.is_symlink():
  540. raise BridgeError("工具附件目录不能是符号链接", 502, "invalid_attachment_directory")
  541. parent.mkdir(mode=0o700, parents=True, exist_ok=True)
  542. extension = mimetypes.guess_extension(mime) or ".bin"
  543. if not re.fullmatch(r"\.[a-zA-Z0-9]{1,10}", extension):
  544. extension = ".bin"
  545. path = directory / (str(uuid.uuid4()) + extension)
  546. directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
  547. parent_fd = os.open(parent, directory_flags)
  548. try:
  549. try:
  550. os.mkdir("yaoyao-bot-bridge", mode=0o700, dir_fd=parent_fd)
  551. except FileExistsError:
  552. pass
  553. directory_fd = os.open("yaoyao-bot-bridge", directory_flags, dir_fd=parent_fd)
  554. try:
  555. os.fchmod(directory_fd, 0o700)
  556. fd = os.open(path.name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=directory_fd)
  557. with os.fdopen(fd, "wb") as stream:
  558. stream.write(data)
  559. finally:
  560. os.close(directory_fd)
  561. finally:
  562. os.close(parent_fd)
  563. return str(path)
  564. def _decode(value: Any) -> bytes:
  565. if not isinstance(value, str):
  566. raise BridgeError("工具附件缺少有效内容", 502, "invalid_result")
  567. try:
  568. return base64.b64decode(value, validate=True)
  569. except (ValueError, TypeError):
  570. raise BridgeError("工具附件编码无效", 502, "invalid_result") from None
  571. def normalize_result(result: dict, binding: Binding) -> str | dict:
  572. """Preserve MCP blocks; adapt pictures to Hermes' native vision envelope."""
  573. parts: list[dict] = []
  574. texts: list[str] = []
  575. has_image = False
  576. def text(value: str):
  577. texts.append(value)
  578. parts.append({"type": "text", "text": value})
  579. if result.get("isError"):
  580. text("工具执行失败:")
  581. blocks = result.get("content", [])
  582. if not isinstance(blocks, list):
  583. raise BridgeError("工具结果 content 无效", 502, "invalid_result")
  584. for block in blocks:
  585. if not isinstance(block, dict):
  586. text(json.dumps(block, ensure_ascii=False))
  587. continue
  588. kind = block.get("type")
  589. if kind == "text":
  590. text(str(block.get("text", "")))
  591. elif kind in {"image", "audio"}:
  592. mime = str(block.get("mimeType") or "application/octet-stream")
  593. data = _decode(block.get("data"))
  594. if kind == "image" and mime in {"image/png", "image/jpeg", "image/gif", "image/webp"}:
  595. has_image = True
  596. parts.append({"type": "image_url", "image_url": {"url": f"data:{mime};base64,{base64.b64encode(data).decode()}"}})
  597. texts.append(f"[图像 {mime},{len(data)} 字节]")
  598. else:
  599. path = _attachment(binding, data, mime)
  600. text(f"附件({mime}):{path}")
  601. elif kind == "resource" and isinstance(block.get("resource"), dict):
  602. resource = block["resource"]
  603. mime = str(resource.get("mimeType") or "application/octet-stream")
  604. if "blob" in resource:
  605. path = _attachment(binding, _decode(resource["blob"]), mime)
  606. text(f"附件({mime},来源 {resource.get('uri', '')}):{path}")
  607. elif "text" in resource:
  608. text(f"资源 {resource.get('uri', '')}\n{resource['text']}")
  609. else:
  610. text(json.dumps(block, ensure_ascii=False))
  611. elif kind == "resource_link":
  612. text(json.dumps(block, ensure_ascii=False))
  613. else:
  614. # Unknown future MCP content stays available as a JSON attachment,
  615. # rather than silently dropping bytes or sending invalid AI parts.
  616. path = _attachment(binding, json.dumps(block, ensure_ascii=False).encode(), "application/json")
  617. text(f"扩展工具结果:{path}")
  618. if "structuredContent" in result:
  619. text(json.dumps(result["structuredContent"], ensure_ascii=False))
  620. if not blocks and "structuredContent" not in result:
  621. text(json.dumps(result, ensure_ascii=False))
  622. summary = "\n".join(texts)
  623. return {"_multimodal": True, "content": parts, "text_summary": summary} if has_image else summary
  624. def list_tools(args: dict, **kwargs) -> str:
  625. try:
  626. if args:
  627. raise BridgeError("查询工具不接受身份或其他参数", 400, "invalid_request")
  628. binding = _resolve(kwargs.get("session_id", ""))
  629. result = _request(binding, "/tools/list")
  630. if _resolve(kwargs.get("session_id", "")) is not binding:
  631. raise BridgeError("本轮工具授权已经更换")
  632. return json.dumps(result, ensure_ascii=False)
  633. except BridgeError as exc:
  634. return json.dumps({"error": str(exc), "code": exc.code}, ensure_ascii=False)
  635. def call_tool(args: dict, **kwargs) -> str | dict:
  636. try:
  637. if not isinstance(args, dict) or set(args) != {"toolId", "arguments"} or not isinstance(args.get("arguments"), dict):
  638. raise BridgeError("调用必须只包含 toolId 和 arguments", 400, "invalid_request")
  639. tool_id = _string(args, "toolId")
  640. binding = _resolve(kwargs.get("session_id", ""))
  641. # The model cannot pick identity, credentials or a replay identifier.
  642. # One UUID per invocation. No automatic retry of side-effecting tools.
  643. invocation = kwargs.get("tool_call_id")
  644. call_id = hashlib.sha256((str(kwargs.get("session_id")) + ":" + invocation).encode()).hexdigest() if isinstance(invocation, str) and invocation else str(uuid.uuid4())
  645. result = _request(binding, "/tools/call", {"toolId": tool_id, "arguments": args["arguments"], "callId": call_id})
  646. # A cancelled or replaced grant may finish in the background. Do not
  647. # release its result to a different turn after an HTTP round trip.
  648. if _resolve(kwargs.get("session_id", "")) is not binding:
  649. raise BridgeError("本轮工具授权已经更换")
  650. return normalize_result(result, binding)
  651. except BridgeError as exc:
  652. return json.dumps({"error": str(exc), "code": exc.code}, ensure_ascii=False)
  653. # Native Hermes remains the only owner of Profile configuration, skills and
  654. # authenticated integrations. The Runner never opens those files itself.
  655. def computer_directive(session_id=None, tool_name=None, args=None, **kwargs):
  656. try:
  657. server = _server()
  658. except BridgeError:
  659. return None
  660. with server._sessions_lock, _lock:
  661. inherited = _children.get(session_id)
  662. sessions = [inherited[0].session] if inherited else [s for sid, s in server._sessions.items()
  663. if session_id in {sid, s.get("session_key"), getattr(s.get("agent"), "session_id", None)}]
  664. managed = next((s for s in sessions if s.get("_yaoyao_computer_policy")), None)
  665. if managed is None:
  666. return None
  667. try:
  668. binding = _resolve(session_id)
  669. except BridgeError:
  670. return {"action": "block", "message": "电脑会话授权已经结束,请在当前 Bot 中发起新一轮。"}
  671. policy = binding.computer_policy
  672. if not policy:
  673. return {"action": "block", "message": "当前轮次缺少电脑权限声明。"}
  674. if policy["mode"] == "profile" or policy["hostAccess"]:
  675. return None
  676. # Skill discovery, vision, and authenticated services retain the Profile's
  677. # existing tool permissions. Host commands/files/UI require Hermes approval.
  678. host_tools = {"terminal", "process", "process_manage", "read_file", "write_file", "patch", "search_files",
  679. "execute_code", "code_execution", "delegate_task", "computer_use", "desktop_project", "session_search"}
  680. host = tool_name in host_tools or str(tool_name).startswith(("browser_", "host_", "yaoyao_computer_copy_file_"))
  681. if not host:
  682. return None
  683. fingerprint = hashlib.sha256(json.dumps([tool_name, args], sort_keys=True, ensure_ascii=False).encode()).hexdigest()
  684. try:
  685. from agent.redact import redact_sensitive_text
  686. details = redact_sensitive_text(json.dumps(args or {}, ensure_ascii=False), force=True)[:4000]
  687. except Exception:
  688. return {"action": "block", "message": "无法安全显示本机操作内容,请使用虚拟机工具或重新发起请求。"}
  689. return {"action": "approve", "message": f"隔离 Bot 请求使用 Hermes 本机工具 {tool_name}。\n具体操作:{details}",
  690. "rule_key": "yaoyao-host:" + fingerprint}
  691. def computer_file(owner, body):
  692. binding = _resolve(_string(body, "session_id"))
  693. if binding.owner != owner or binding.generation != _string(body, "generation") or not binding.computer_policy:
  694. raise BridgeError("文件请求不属于当前电脑会话")
  695. action, raw = body.get("action"), _string(body, "path", 4096)
  696. if action not in {"read", "write"} or "\0" in raw:
  697. raise BridgeError("文件请求格式无效", 400)
  698. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  699. context = set_hermes_home_override(binding.profile_home)
  700. try:
  701. cwd = Path(binding.session.get("cwd") or binding.profile_home)
  702. path = Path(raw).expanduser()
  703. path = (cwd / path).resolve() if not path.is_absolute() else path.resolve()
  704. # Respect Hermes' internal protected paths as well as regular-file and
  705. # size bounds; model-selected paths never become configuration inputs.
  706. from tools.file_tools import _check_sensitive_path, _check_protected_instruction_write, _check_approval_required_write
  707. from agent.file_safety import get_read_block_error
  708. error = get_read_block_error(str(path)) if action == "read" else _check_sensitive_path(str(path), str(binding.agent.session_id))
  709. if action == "write" and not error:
  710. error = (_check_protected_instruction_write([str(path)], str(binding.agent.session_id))
  711. or _check_approval_required_write([str(path)], str(binding.agent.session_id)))
  712. if error:
  713. raise BridgeError("该文件不在 Hermes 允许的文件访问范围内")
  714. limit = 25 * 1024 * 1024
  715. if action == "read":
  716. import stat
  717. fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0))
  718. with os.fdopen(fd, "rb") as stream:
  719. info = os.fstat(stream.fileno())
  720. if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
  721. raise BridgeError("只支持不超过 25 MiB 的普通文件", 400)
  722. data = stream.read(limit + 1)
  723. if len(data) > limit:
  724. raise BridgeError("文件超过 25 MiB", 413)
  725. result = {"ok": True, "data": base64.b64encode(data).decode()}
  726. else:
  727. encoded = body.get("data")
  728. if not isinstance(encoded, str) or len(encoded) > (limit + 2) // 3 * 4:
  729. raise BridgeError("文件超过 25 MiB", 413)
  730. try:
  731. data = base64.b64decode(encoded, validate=True)
  732. except ValueError:
  733. raise BridgeError("文件编码无效", 400) from None
  734. if len(data) > limit:
  735. raise BridgeError("文件超过 25 MiB", 413)
  736. _resolve(binding.session_id)
  737. path.parent.mkdir(parents=True, exist_ok=True)
  738. # Atomic replacement never follows an existing destination symlink.
  739. import tempfile
  740. fd, temporary = tempfile.mkstemp(prefix=".yaoyao-transfer-", dir=path.parent)
  741. try:
  742. with os.fdopen(fd, "wb") as stream:
  743. stream.write(data)
  744. _resolve(binding.session_id)
  745. os.replace(temporary, path)
  746. finally:
  747. Path(temporary).unlink(missing_ok=True)
  748. result = {"ok": True}
  749. if _resolve(binding.session_id) is not binding:
  750. raise BridgeError("文件所属轮次已经结束")
  751. return result
  752. finally:
  753. reset_hermes_home_override(context)
  754. async def extract_memory(profile, prompt):
  755. import asyncio
  756. if not isinstance(profile, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", profile):
  757. raise BridgeError("Profile 名称无效", 400)
  758. if not isinstance(prompt, str) or not 0 < len(prompt) <= 65000:
  759. raise BridgeError("记忆提炼输入无效", 400)
  760. from hermes_cli.profiles import get_profile_dir, profile_exists
  761. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  762. if not profile_exists(profile):
  763. raise BridgeError("Hermes Profile 不存在", 404)
  764. context = set_hermes_home_override(get_profile_dir(profile))
  765. try:
  766. from agent.auxiliary_client import async_call_llm, extract_content_or_reasoning
  767. from hermes_cli.config import load_config_readonly
  768. from hermes_cli.runtime_provider import resolve_runtime_provider
  769. model = load_config_readonly().get("model") or {}
  770. if not isinstance(model, dict) or not model.get("default"):
  771. raise BridgeError("Hermes Profile 尚未配置模型", 409)
  772. runtime = resolve_runtime_provider(requested=model.get("provider"), target_model=model["default"],
  773. explicit_base_url=model.get("base_url"), explicit_api_key=model.get("api_key"))
  774. # An HTTP request has no agent turn context: never borrow the last
  775. # multiplexed Profile's runtime from the auxiliary client's mirrors.
  776. response = await asyncio.wait_for(async_call_llm(task="compression", messages=[
  777. {"role": "system", "content": "仅从给定材料提炼记忆。不调用工具,不补充未经确认的事实。"},
  778. {"role": "user", "content": prompt}], tools=[], max_tokens=4096, timeout=90,
  779. main_runtime={**runtime, "model": model["default"]}), timeout=90)
  780. return {"text": extract_content_or_reasoning(response)}
  781. finally:
  782. reset_hermes_home_override(context)