bridge_runtime.py 43 KB

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